quartz: Add tests for avi splitter.
[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  * Copyright 2008 Eric Pouech
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22  */
23
24 /* 
25   API implementation status:
26   
27   Messages (ANSI versions not done yet)
28   + EM_AUTOURLDETECT 2.0
29   + EM_CANPASTE
30   + EM_CANREDO 2.0
31   + EM_CANUNDO
32   + EM_CHARFROMPOS
33   - EM_DISPLAYBAND
34   + EM_EMPTYUNDOBUFFER
35   + EM_EXGETSEL
36   + EM_EXLIMITTEXT
37   + EM_EXLINEFROMCHAR
38   + EM_EXSETSEL
39   + EM_FINDTEXT (only FR_DOWN flag implemented)
40   + EM_FINDTEXTEX (only FR_DOWN flag implemented)
41   - EM_FINDWORDBREAK
42   - EM_FMTLINES
43   - EM_FORMATRANGE
44   + EM_GETAUTOURLDETECT 2.0
45   - EM_GETBIDIOPTIONS 3.0
46   - EM_GETCHARFORMAT (partly done)
47   - EM_GETEDITSTYLE
48   + EM_GETEVENTMASK
49   + EM_GETFIRSTVISIBLELINE (can be optimized if needed)
50   - EM_GETIMECOLOR 1.0asian
51   - EM_GETIMECOMPMODE 2.0
52   - EM_GETIMEOPTIONS 1.0asian
53   - EM_GETIMESTATUS
54   - EM_GETLANGOPTIONS 2.0
55   + EM_GETLIMITTEXT
56   + EM_GETLINE
57   + EM_GETLINECOUNT   returns number of rows, not of paragraphs
58   + EM_GETMODIFY
59   - EM_GETOLEINTERFACE
60   + EM_GETOPTIONS
61   + EM_GETPARAFORMAT
62   + EM_GETPASSWORDCHAR 2.0
63   - EM_GETPUNCTUATION 1.0asian
64   + EM_GETRECT
65   - EM_GETREDONAME 2.0
66   + EM_GETSEL
67   + EM_GETSELTEXT (ANSI&Unicode)
68   + EM_GETSCROLLPOS 3.0 (only Y value valid)
69 ! - EM_GETTHUMB
70   + EM_GETTEXTEX 2.0
71   + EM_GETTEXTLENGTHEX (GTL_PRECISE unimplemented)
72   - EM_GETTEXTMODE 2.0
73 ? + EM_GETTEXTRANGE (ANSI&Unicode)
74   - EM_GETTYPOGRAPHYOPTIONS 3.0
75   - EM_GETUNDONAME
76   + EM_GETWORDBREAKPROC
77   - EM_GETWORDBREAKPROCEX
78   - EM_GETWORDWRAPMODE 1.0asian
79   + EM_GETZOOM 3.0
80   + EM_HIDESELECTION
81   + EM_LIMITTEXT (Also called EM_SETLIMITTEXT)
82   + EM_LINEFROMCHAR
83   + EM_LINEINDEX
84   + EM_LINELENGTH
85   + EM_LINESCROLL
86   - EM_PASTESPECIAL
87   + EM_POSFROMCHAR
88   + EM_REDO 2.0
89   + EM_REQUESTRESIZE
90   + EM_REPLACESEL (proper style?) ANSI&Unicode
91   + EM_SCROLL
92   + EM_SCROLLCARET
93   - EM_SELECTIONTYPE
94   - EM_SETBIDIOPTIONS 3.0
95   + EM_SETBKGNDCOLOR
96   + EM_SETCHARFORMAT (partly done, no ANSI)
97   - EM_SETEDITSTYLE
98   + EM_SETEVENTMASK (few notifications supported)
99   - EM_SETFONTSIZE
100   - EM_SETIMECOLOR 1.0asian
101   - EM_SETIMEOPTIONS 1.0asian
102   - EM_SETLANGOPTIONS 2.0
103   - EM_SETLIMITTEXT
104   + EM_SETMODIFY (not sure if implementation is correct)
105   - EM_SETOLECALLBACK
106   + EM_SETOPTIONS (partially implemented)
107   - EM_SETPALETTE 2.0
108   + EM_SETPARAFORMAT
109   + EM_SETPASSWORDCHAR 2.0
110   - EM_SETPUNCTUATION 1.0asian
111   + EM_SETREADONLY no beep on modification attempt
112   + EM_SETRECT
113   + EM_SETRECTNP (EM_SETRECT without repainting)
114   + EM_SETSEL
115   + EM_SETSCROLLPOS 3.0
116   - EM_SETTABSTOPS 3.0
117   - EM_SETTARGETDEVICE (partial)
118   + EM_SETTEXTEX 3.0 (proper style?)
119   - EM_SETTEXTMODE 2.0
120   - EM_SETTYPOGRAPHYOPTIONS 3.0
121   + EM_SETUNDOLIMIT 2.0
122   + EM_SETWORDBREAKPROC (used only for word movement at the moment)
123   - EM_SETWORDBREAKPROCEX
124   - EM_SETWORDWRAPMODE 1.0asian
125   + EM_SETZOOM 3.0
126   + EM_SHOWSCROLLBAR 2.0
127   + EM_STOPGROUPTYPING 2.0
128   + EM_STREAMIN
129   + EM_STREAMOUT
130   + EM_UNDO
131   + WM_CHAR
132   + WM_CLEAR
133   + WM_COPY
134   + WM_CUT
135   + WM_GETDLGCODE (the current implementation is incomplete)
136   + WM_GETTEXT (ANSI&Unicode)
137   + WM_GETTEXTLENGTH (ANSI version sucks)
138   + WM_PASTE
139   + WM_SETFONT
140   + WM_SETTEXT (resets undo stack !) (proper style?) ANSI&Unicode
141   - WM_STYLECHANGING
142   - WM_STYLECHANGED (things like read-only flag)
143   - WM_UNICHAR
144   
145   Notifications
146   
147   * EN_CHANGE (sent from the wrong place)
148   - EN_CORRECTTEXT
149   - EN_DROPFILES
150   - EN_ERRSPACE
151   - EN_HSCROLL
152   - EN_IMECHANGE
153   + EN_KILLFOCUS
154   - EN_LINK
155   - EN_MAXTEXT
156   - EN_MSGFILTER
157   - EN_OLEOPFAILED
158   - EN_PROTECTED
159   + EN_REQUESTRESIZE
160   - EN_SAVECLIPBOARD
161   + EN_SELCHANGE 
162   + EN_SETFOCUS
163   - EN_STOPNOUNDO
164   * EN_UPDATE (sent from the wrong place)
165   - EN_VSCROLL
166   
167   Styles
168   
169   - ES_AUTOHSCROLL
170   - ES_AUTOVSCROLL
171   - ES_CENTER
172   + ES_DISABLENOSCROLL (scrollbar is always visible)
173   - ES_EX_NOCALLOLEINIT
174   - ES_LEFT
175   - ES_MULTILINE (currently single line controls aren't supported)
176   - ES_NOIME
177   - ES_READONLY (I'm not sure if beeping is the proper behaviour)
178   - ES_RIGHT
179   - ES_SAVESEL
180   - ES_SELFIME
181   - ES_SUNKEN
182   - ES_VERTICAL
183   - ES_WANTRETURN (don't know how to do WM_GETDLGCODE part)
184   - WS_SETFONT
185   - WS_HSCROLL
186   + WS_VSCROLL
187 */
188
189 /*
190  * RICHED20 TODO (incomplete):
191  *
192  * - messages/styles/notifications listed above 
193  * - add remaining CHARFORMAT/PARAFORMAT fields
194  * - right/center align should strip spaces from the beginning
195  * - pictures/OLE objects (not just smiling faces that lack API support ;-) )
196  * - COM interface (looks like a major pain in the TODO list)
197  * - calculate heights of pictures (half-done)
198  * - horizontal scrolling (not even started)
199  * - hysteresis during wrapping (related to scrollbars appearing/disappearing)
200  * - find/replace
201  * - how to implement EM_FORMATRANGE and EM_DISPLAYBAND ? (Mission Impossible)
202  * - italic caret with italic fonts
203  * - IME
204  * - most notifications aren't sent at all (the most important ones are)
205  * - when should EN_SELCHANGE be sent after text change ? (before/after EN_UPDATE?)
206  * - WM_SETTEXT may use wrong style (but I'm 80% sure it's OK)
207  * - EM_GETCHARFORMAT with SCF_SELECTION may not behave 100% like in original (but very close)
208  * - full justification
209  * - hyphenation
210  * - tables
211  * - ListBox & ComboBox not implemented
212  *
213  * Bugs that are probably fixed, but not so easy to verify:
214  * - EN_UPDATE/EN_CHANGE are handled very incorrectly (should be OK now)
215  * - undo for ME_JoinParagraphs doesn't store paragraph format ? (it does)
216  * - check/fix artificial EOL logic (bCursorAtEnd, hardly logical)
217  * - caret shouldn't be displayed when selection isn't empty
218  * - check refcounting in style management functions (looks perfect now, but no bugs is suspicious)
219  * - undo for setting default format (done, might be buggy)
220  * - styles might be not released properly (looks like they work like charm, but who knows?
221  *
222  */
223
224 #include "editor.h"
225 #include "commdlg.h"
226 #include "winreg.h"
227 #define NO_SHLWAPI_STREAM 
228 #include "shlwapi.h"
229 #include "rtf.h"
230 #include "imm.h"
231 #include "res.h"
232
233 #define STACK_SIZE_DEFAULT  100
234 #define STACK_SIZE_MAX     1000
235
236 #define TEXT_LIMIT_DEFAULT 32767
237  
238 WINE_DEFAULT_DEBUG_CHANNEL(richedit);
239
240 static BOOL ME_RegisterEditorClass(HINSTANCE);
241
242 static const WCHAR RichEdit20W[] = {'R', 'i', 'c', 'h', 'E', 'd', 'i', 't', '2', '0', 'W', 0};
243 static const WCHAR RichEdit50W[] = {'R', 'i', 'c', 'h', 'E', 'd', 'i', 't', '5', '0', 'W', 0};
244 static const WCHAR REListBox20W[] = {'R','E','L','i','s','t','B','o','x','2','0','W', 0};
245 static const WCHAR REComboBox20W[] = {'R','E','C','o','m','b','o','B','o','x','2','0','W', 0};
246 static HCURSOR hLeft;
247
248 int me_debug = 0;
249 HANDLE me_heap = NULL;
250
251 static BOOL ME_ListBoxRegistered = FALSE;
252 static BOOL ME_ComboBoxRegistered = FALSE;
253
254 static inline int is_version_nt(void)
255 {
256     return !(GetVersion() & 0x80000000);
257 }
258
259 static ME_TextBuffer *ME_MakeText(void) {
260   
261   ME_TextBuffer *buf = ALLOC_OBJ(ME_TextBuffer);
262
263   ME_DisplayItem *p1 = ME_MakeDI(diTextStart);
264   ME_DisplayItem *p2 = ME_MakeDI(diTextEnd);
265   
266   p1->prev = NULL;
267   p1->next = p2;
268   p2->prev = p1;
269   p2->next = NULL;
270   p1->member.para.next_para = p2;
271   p2->member.para.prev_para = p1;
272   p2->member.para.nCharOfs = 0;  
273   
274   buf->pFirst = p1;
275   buf->pLast = p2;
276   buf->pCharStyle = NULL;
277   
278   return buf;
279 }
280
281
282 static LRESULT ME_StreamInText(ME_TextEditor *editor, DWORD dwFormat, ME_InStream *stream, ME_Style *style)
283 {
284   WCHAR wszText[STREAMIN_BUFFER_SIZE+1];
285   WCHAR *pText;
286   
287   TRACE("%08x %p\n", dwFormat, stream);
288   
289   do {
290     long nWideChars = 0;
291
292     if (!stream->dwSize)
293     {
294       ME_StreamInFill(stream);
295       if (stream->editstream->dwError)
296         break;
297       if (!stream->dwSize)
298         break;
299     }
300       
301     if (!(dwFormat & SF_UNICODE))
302     {
303       /* FIXME? this is doomed to fail on true MBCS like UTF-8, luckily they're unlikely to be used as CP_ACP */
304       nWideChars = MultiByteToWideChar(CP_ACP, 0, stream->buffer, stream->dwSize, wszText, STREAMIN_BUFFER_SIZE);
305       pText = wszText;
306     }
307     else
308     {
309       nWideChars = stream->dwSize >> 1;
310       pText = (WCHAR *)stream->buffer;
311     }
312     
313     ME_InsertTextFromCursor(editor, 0, pText, nWideChars, style);
314     if (stream->dwSize == 0)
315       break;
316     stream->dwSize = 0;
317   } while(1);
318   ME_CommitUndo(editor);
319   ME_UpdateRepaint(editor);
320   return 0;
321 }
322
323 static void ME_RTFCharAttrHook(RTF_Info *info)
324 {
325   CHARFORMAT2W fmt;
326   fmt.cbSize = sizeof(fmt);
327   fmt.dwMask = 0;
328   fmt.dwEffects = 0;
329
330   switch(info->rtfMinor)
331   {
332     case rtfPlain:
333       /* FIXME add more flags once they're implemented */
334       fmt.dwMask = CFM_BOLD | CFM_ITALIC | CFM_UNDERLINETYPE | CFM_STRIKEOUT | CFM_COLOR | CFM_BACKCOLOR | CFM_SIZE | CFM_WEIGHT;
335       fmt.dwEffects = CFE_AUTOCOLOR | CFE_AUTOBACKCOLOR;
336       fmt.yHeight = 12*20; /* 12pt */
337       fmt.wWeight = FW_NORMAL;
338       fmt.bUnderlineType = CFU_UNDERLINENONE;
339       break;
340     case rtfBold:
341       fmt.dwMask = CFM_BOLD | CFM_WEIGHT;
342       fmt.dwEffects = info->rtfParam ? CFE_BOLD : 0;
343       fmt.wWeight = info->rtfParam ? FW_BOLD : FW_NORMAL;
344       break;
345     case rtfItalic:
346       fmt.dwMask = CFM_ITALIC;
347       fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
348       break;
349     case rtfUnderline:
350       fmt.dwMask = CFM_UNDERLINETYPE;
351       fmt.bUnderlineType = info->rtfParam ? CFU_CF1UNDERLINE : CFU_UNDERLINENONE;
352       break;
353     case rtfDotUnderline:
354       fmt.dwMask = CFM_UNDERLINETYPE;
355       fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEDOTTED : CFU_UNDERLINENONE;
356       break;
357     case rtfDbUnderline:
358       fmt.dwMask = CFM_UNDERLINETYPE;
359       fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEDOUBLE : CFU_UNDERLINENONE;
360       break;
361     case rtfWordUnderline:
362       fmt.dwMask = CFM_UNDERLINETYPE;
363       fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEWORD : CFU_UNDERLINENONE;
364       break;
365     case rtfNoUnderline:
366       fmt.dwMask = CFM_UNDERLINETYPE;
367       fmt.bUnderlineType = CFU_UNDERLINENONE;
368       break;
369     case rtfStrikeThru:
370       fmt.dwMask = CFM_STRIKEOUT;
371       fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
372       break;
373     case rtfSubScript:
374     case rtfSuperScript:
375     case rtfSubScrShrink:
376     case rtfSuperScrShrink:
377     case rtfNoSuperSub:
378       fmt.dwMask = CFM_SUBSCRIPT|CFM_SUPERSCRIPT;
379       if (info->rtfMinor == rtfSubScrShrink) fmt.dwEffects = CFE_SUBSCRIPT;
380       if (info->rtfMinor == rtfSuperScrShrink) fmt.dwEffects = CFE_SUPERSCRIPT;
381       if (info->rtfMinor == rtfNoSuperSub) fmt.dwEffects = 0;
382       break;
383     case rtfInvisible:
384       fmt.dwMask = CFM_HIDDEN;
385       fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
386       break;
387     case rtfBackColor:
388       fmt.dwMask = CFM_BACKCOLOR;
389       fmt.dwEffects = 0;
390       if (info->rtfParam == 0)
391         fmt.dwEffects = CFE_AUTOBACKCOLOR;
392       else if (info->rtfParam != rtfNoParam)
393       {
394         RTFColor *c = RTFGetColor(info, info->rtfParam);
395         fmt.crTextColor = (c->rtfCBlue<<16)|(c->rtfCGreen<<8)|(c->rtfCRed);
396       }
397       break;
398     case rtfForeColor:
399       fmt.dwMask = CFM_COLOR;
400       fmt.dwEffects = 0;
401       if (info->rtfParam == 0)
402         fmt.dwEffects = CFE_AUTOCOLOR;
403       else if (info->rtfParam != rtfNoParam)
404       {
405         RTFColor *c = RTFGetColor(info, info->rtfParam);
406         if (c)
407           fmt.crTextColor = (c->rtfCBlue<<16)|(c->rtfCGreen<<8)|(c->rtfCRed);
408         else
409           fmt.crTextColor = 0;
410       }
411       break;
412     case rtfFontNum:
413       if (info->rtfParam != rtfNoParam)
414       {
415         RTFFont *f = RTFGetFont(info, info->rtfParam);
416         if (f)
417         {
418           MultiByteToWideChar(CP_ACP, 0, f->rtfFName, -1, fmt.szFaceName, sizeof(fmt.szFaceName)/sizeof(WCHAR));
419           fmt.szFaceName[sizeof(fmt.szFaceName)/sizeof(WCHAR)-1] = '\0';
420           fmt.bCharSet = f->rtfFCharSet;
421           fmt.dwMask = CFM_FACE | CFM_CHARSET;
422           fmt.bPitchAndFamily = f->rtfFPitch | (f->rtfFFamily << 4);
423         }
424       }
425       break;
426     case rtfFontSize:
427       fmt.dwMask = CFM_SIZE;
428       if (info->rtfParam != rtfNoParam)
429         fmt.yHeight = info->rtfParam*10;
430       break;
431   }
432   if (fmt.dwMask) {
433     ME_Style *style2;
434     RTFFlushOutputBuffer(info);
435     /* FIXME too slow ? how come ? */
436     style2 = ME_ApplyStyle(info->style, &fmt);
437     ME_ReleaseStyle(info->style);
438     info->style = style2;
439     info->styleChanged = TRUE;
440   }
441 }
442
443 /* FIXME this function doesn't get any information about context of the RTF tag, which is very bad,
444    the same tags mean different things in different contexts */
445 static void ME_RTFParAttrHook(RTF_Info *info)
446 {
447   PARAFORMAT2 fmt;
448   fmt.cbSize = sizeof(fmt);
449   fmt.dwMask = 0;
450   
451   switch(info->rtfMinor)
452   {
453   case rtfParDef: /* restores default paragraph attributes */
454     fmt.dwMask = PFM_ALIGNMENT | PFM_BORDER | PFM_LINESPACING | PFM_TABSTOPS | PFM_OFFSET |
455         PFM_RIGHTINDENT | PFM_SPACEAFTER | PFM_SPACEBEFORE | PFM_STARTINDENT;
456     /* TODO: numbering, shading */
457     fmt.wAlignment = PFA_LEFT;
458     fmt.cTabCount = 0;
459     fmt.dxOffset = fmt.dxStartIndent = fmt.dxRightIndent = 0;
460     fmt.wBorderWidth = fmt.wBorders = 0;
461     fmt.wBorderSpace = 0;
462     fmt.bLineSpacingRule = 0;
463     fmt.dySpaceBefore = fmt.dySpaceAfter = 0;
464     fmt.dyLineSpacing = 0;
465     RTFFlushOutputBuffer(info);
466     ME_GetParagraph(info->editor->pCursors[0].pRun)->member.para.bTable = FALSE;
467     break;
468   case rtfInTable:
469   {
470     ME_DisplayItem *para;
471     
472     RTFFlushOutputBuffer(info);
473     para = ME_GetParagraph(info->editor->pCursors[0].pRun);
474     assert(para->member.para.pCells);
475     para->member.para.bTable = TRUE;
476     return;
477   }
478   case rtfFirstIndent:
479     ME_GetSelectionParaFormat(info->editor, &fmt);
480     fmt.dwMask |= PFM_STARTINDENT | PFM_OFFSET;
481     fmt.dxStartIndent += info->rtfParam;
482     fmt.dxOffset = -info->rtfParam;
483     break;
484   case rtfLeftIndent:
485     /* we assume rtfLeftIndent is always specified before rtfFirstIndent */
486     ME_GetSelectionParaFormat(info->editor, &fmt);
487     fmt.dwMask |= PFM_STARTINDENT;
488     fmt.dxStartIndent = info->rtfParam;
489     fmt.dxOffset = 0;
490     break;
491   case rtfRightIndent:
492     fmt.dwMask = PFM_RIGHTINDENT;
493     fmt.dxRightIndent = info->rtfParam;
494     break;
495   case rtfQuadLeft:
496   case rtfQuadJust:
497     fmt.dwMask = PFM_ALIGNMENT;
498     fmt.wAlignment = PFA_LEFT;
499     break;
500   case rtfQuadRight:
501     fmt.dwMask = PFM_ALIGNMENT;
502     fmt.wAlignment = PFA_RIGHT;
503     break;
504   case rtfQuadCenter:
505     fmt.dwMask = PFM_ALIGNMENT;
506     fmt.wAlignment = PFA_CENTER;
507     break;
508   case rtfTabPos:
509     ME_GetSelectionParaFormat(info->editor, &fmt);
510     if (!(fmt.dwMask & PFM_TABSTOPS))
511     {
512       fmt.dwMask |= PFM_TABSTOPS;
513       fmt.cTabCount = 0;
514     }
515     if (fmt.cTabCount < MAX_TAB_STOPS)
516       fmt.rgxTabs[fmt.cTabCount++] = info->rtfParam;
517     break;
518   case rtfKeep:
519     fmt.dwMask = PFM_KEEP;
520     fmt.wEffects = PFE_KEEP;
521     break;
522   case rtfNoWidowControl:
523     fmt.dwMask = PFM_NOWIDOWCONTROL;
524     fmt.wEffects = PFE_NOWIDOWCONTROL;
525     break;
526   case rtfKeepNext:
527     fmt.dwMask = PFM_KEEPNEXT;
528     fmt.wEffects = PFE_KEEPNEXT;
529     break;
530   case rtfSpaceAfter:
531     fmt.dwMask = PFM_SPACEAFTER;
532     fmt.dySpaceAfter = info->rtfParam;
533     break;
534   case rtfSpaceBefore:
535     fmt.dwMask = PFM_SPACEBEFORE;
536     fmt.dySpaceBefore = info->rtfParam;
537     break;
538   case rtfSpaceBetween:
539     fmt.dwMask = PFM_LINESPACING;
540     if ((int)info->rtfParam > 0)
541     {
542       fmt.dyLineSpacing = info->rtfParam;
543       fmt.bLineSpacingRule = 3;
544     }
545     else
546     {
547       fmt.dyLineSpacing = info->rtfParam;
548       fmt.bLineSpacingRule = 4;
549     }
550   case rtfSpaceMultiply:
551     fmt.dwMask = PFM_LINESPACING;
552     fmt.dyLineSpacing = info->rtfParam * 20;
553     fmt.bLineSpacingRule = 5;
554     break;
555   case rtfParBullet:
556     fmt.dwMask = PFM_NUMBERING;
557     fmt.wNumbering = PFN_BULLET;
558     break;
559   case rtfParSimple:
560     fmt.dwMask = PFM_NUMBERING;
561     fmt.wNumbering = 2; /* FIXME: MSDN says it's not used ?? */
562     break;
563   case rtfParNumDecimal:
564     fmt.dwMask = PFM_NUMBERING;
565     fmt.wNumbering = 2; /* FIXME: MSDN says it's not used ?? */
566     break;
567   case rtfParNumIndent:
568     fmt.dwMask = PFM_NUMBERINGTAB;
569     fmt.wNumberingTab = info->rtfParam;
570     break;
571   case rtfParNumStartAt:
572     fmt.dwMask = PFM_NUMBERINGSTART;
573     fmt.wNumberingStart = info->rtfParam;
574     break;
575   case rtfBorderLeft:
576     ME_GetSelectionParaFormat(info->editor, &fmt);
577     if (!(fmt.dwMask & PFM_BORDER))
578     {
579       fmt.dwMask |= PFM_BORDER;
580       fmt.wBorderSpace = 0;
581       fmt.wBorderWidth = 1;
582       fmt.wBorders = 0;
583     }
584     fmt.wBorders |= 1;
585     break;
586   case rtfBorderRight:
587     ME_GetSelectionParaFormat(info->editor, &fmt);
588     if (!(fmt.dwMask & PFM_BORDER))
589     {
590       fmt.dwMask |= PFM_BORDER;
591       fmt.wBorderSpace = 0;
592       fmt.wBorderWidth = 1;
593       fmt.wBorders = 0;
594     }
595     fmt.wBorders |= 2;
596     break;
597   case rtfBorderTop:
598     ME_GetSelectionParaFormat(info->editor, &fmt);
599     if (!(fmt.dwMask & PFM_BORDER))
600     {
601       fmt.dwMask |= PFM_BORDER;
602       fmt.wBorderSpace = 0;
603       fmt.wBorderWidth = 1;
604       fmt.wBorders = 0;
605     }
606     fmt.wBorders |= 4;
607     break;
608   case rtfBorderBottom:
609     ME_GetSelectionParaFormat(info->editor, &fmt);
610     if (!(fmt.dwMask & PFM_BORDER))
611     {
612       fmt.dwMask |= PFM_BORDER;
613       fmt.wBorderSpace = 0;
614       fmt.wBorderWidth = 1;
615       fmt.wBorders = 0;
616     }
617     fmt.wBorders |= 8;
618     break;
619   case rtfBorderSingle:
620     ME_GetSelectionParaFormat(info->editor, &fmt);
621     /* we assume that borders have been created before (RTF spec) */
622     fmt.wBorders &= ~0x700;
623     fmt.wBorders |= 1 << 8;
624     break;
625   case rtfBorderThick:
626     ME_GetSelectionParaFormat(info->editor, &fmt);
627     /* we assume that borders have been created before (RTF spec) */
628     fmt.wBorders &= ~0x700;
629     fmt.wBorders |= 2 << 8;
630     break;
631   case rtfBorderShadow:
632     ME_GetSelectionParaFormat(info->editor, &fmt);
633     /* we assume that borders have been created before (RTF spec) */
634     fmt.wBorders &= ~0x700;
635     fmt.wBorders |= 10 << 8;
636     break;
637   case rtfBorderDouble:
638     ME_GetSelectionParaFormat(info->editor, &fmt);
639     /* we assume that borders have been created before (RTF spec) */
640     fmt.wBorders &= ~0x700;
641     fmt.wBorders |= 7 << 8;
642     break;
643   case rtfBorderDot:
644     ME_GetSelectionParaFormat(info->editor, &fmt);
645     /* we assume that borders have been created before (RTF spec) */
646     fmt.wBorders &= ~0x700;
647     fmt.wBorders |= 11 << 8;
648     break;
649   case rtfBorderWidth:
650     ME_GetSelectionParaFormat(info->editor, &fmt);
651     /* we assume that borders have been created before (RTF spec) */
652     fmt.wBorderWidth |= ((info->rtfParam / 15) & 7) << 8;
653     break;
654   case rtfBorderSpace:
655     ME_GetSelectionParaFormat(info->editor, &fmt);
656     /* we assume that borders have been created before (RTF spec) */
657     fmt.wBorderSpace = info->rtfParam;
658     break;
659   }  
660   if (fmt.dwMask) {
661     RTFFlushOutputBuffer(info);
662     /* FIXME too slow ? how come ?*/
663     ME_SetSelectionParaFormat(info->editor, &fmt);
664   }
665 }
666
667 static void ME_RTFTblAttrHook(RTF_Info *info)
668 {
669   ME_DisplayItem *para;
670   
671   switch (info->rtfMinor)
672   {
673     case rtfRowDef:
674       RTFFlushOutputBuffer(info);
675       para = ME_GetParagraph(info->editor->pCursors[0].pRun);
676       
677       /* Release possibly inherited cell definitions */
678       ME_DestroyTableCellList(para);
679       
680       para->member.para.pCells = ALLOC_OBJ(ME_TableCell);
681       para->member.para.pCells->nRightBoundary = 0;
682       para->member.para.pCells->next = NULL;
683       para->member.para.pLastCell = para->member.para.pCells;
684       break;
685     case rtfCellPos:
686       RTFFlushOutputBuffer(info);
687       para = ME_GetParagraph(info->editor->pCursors[0].pRun);
688       
689       if (para->member.para.pLastCell->nRightBoundary)
690       {
691         ME_TableCell *pCell = ALLOC_OBJ(ME_TableCell);
692         
693         pCell->next = NULL;
694         para->member.para.pLastCell->next = pCell;
695         para->member.para.pLastCell = pCell;
696       }
697       para->member.para.pLastCell->nRightBoundary = info->rtfParam;
698       break;
699   }
700 }
701
702 static BOOL ME_RTFInsertOleObject(RTF_Info *info, HENHMETAFILE hemf, HBITMAP hbmp,
703                                   const SIZEL* sz)
704 {
705   LPOLEOBJECT         lpObject = NULL;
706   LPSTORAGE           lpStorage = NULL;
707   LPOLECLIENTSITE     lpClientSite = NULL;
708   LPDATAOBJECT        lpDataObject = NULL;
709   LPOLECACHE          lpOleCache = NULL;
710   STGMEDIUM           stgm;
711   FORMATETC           fm;
712   CLSID               clsid;
713   BOOL                ret = FALSE;
714   DWORD               conn;
715
716   if (hemf)
717   {
718       stgm.tymed = TYMED_ENHMF;
719       stgm.u.hEnhMetaFile = hemf;
720       fm.cfFormat = CF_ENHMETAFILE;
721   }
722   else if (hbmp)
723   {
724       stgm.tymed = TYMED_GDI;
725       stgm.u.hBitmap = hbmp;
726       fm.cfFormat = CF_BITMAP;
727   }
728   stgm.pUnkForRelease = NULL;
729
730   fm.ptd = NULL;
731   fm.dwAspect = DVASPECT_CONTENT;
732   fm.lindex = -1;
733   fm.tymed = stgm.tymed;
734
735   if (!info->lpRichEditOle)
736   {
737     CreateIRichEditOle(info->editor, (VOID**)&info->lpRichEditOle);
738   }
739
740   if (OleCreateDefaultHandler(&CLSID_NULL, NULL, &IID_IOleObject, (void**)&lpObject) == S_OK &&
741 #if 0
742       /* FIXME: enable it when rich-edit properly implements this method */
743       IRichEditOle_GetClientSite(info->lpRichEditOle, &lpClientSite) == S_OK &&
744       IOleObject_SetClientSite(lpObject, lpClientSite) == S_OK &&
745 #endif
746       IOleObject_GetUserClassID(lpObject, &clsid) == S_OK &&
747       IOleObject_QueryInterface(lpObject, &IID_IOleCache, (void**)&lpOleCache) == S_OK &&
748       IOleCache_Cache(lpOleCache, &fm, 0, &conn) == S_OK &&
749       IOleObject_QueryInterface(lpObject, &IID_IDataObject, (void**)&lpDataObject) == S_OK &&
750       IDataObject_SetData(lpDataObject, &fm, &stgm, TRUE) == S_OK)
751   {
752     REOBJECT            reobject;
753
754     reobject.cbStruct = sizeof(reobject);
755     reobject.cp = REO_CP_SELECTION;
756     reobject.clsid = clsid;
757     reobject.poleobj = lpObject;
758     reobject.pstg = lpStorage;
759     reobject.polesite = lpClientSite;
760     /* convert from twips to .01 mm */
761     reobject.sizel.cx = MulDiv(sz->cx, 254, 144);
762     reobject.sizel.cy = MulDiv(sz->cy, 254, 144);
763     reobject.dvaspect = DVASPECT_CONTENT;
764     reobject.dwFlags = 0; /* FIXME */
765     reobject.dwUser = 0;
766
767     /* FIXME: could be simpler */
768     ret = IRichEditOle_InsertObject(info->lpRichEditOle, &reobject) == S_OK;
769   }
770
771   if (lpObject)       IOleObject_Release(lpObject);
772   if (lpClientSite)   IOleClientSite_Release(lpClientSite);
773   if (lpStorage)      IStorage_Release(lpStorage);
774   if (lpDataObject)   IDataObject_Release(lpDataObject);
775   if (lpOleCache)     IOleCache_Release(lpOleCache);
776
777   return ret;
778 }
779
780 static void ME_RTFReadPictGroup(RTF_Info *info)
781 {
782   SIZEL         sz;
783   BYTE*         buffer = NULL;
784   unsigned      bufsz, bufidx;
785   BOOL          flip;
786   BYTE          val;
787   METAFILEPICT  mfp;
788   HENHMETAFILE  hemf;
789   HBITMAP       hbmp;
790   enum gfxkind {gfx_unknown = 0, gfx_enhmetafile, gfx_metafile, gfx_dib} gfx = gfx_unknown;
791
792   RTFGetToken (info);
793   if (info->rtfClass == rtfEOF)
794     return;
795   mfp.mm = MM_TEXT;
796   /* fetch picture type */
797   if (RTFCheckMM (info, rtfPictAttr, rtfWinMetafile))
798   {
799     mfp.mm = info->rtfParam;
800     gfx = gfx_metafile;
801   }
802   else if (RTFCheckMM (info, rtfPictAttr, rtfDevIndBitmap))
803   {
804     if (info->rtfParam != 0) FIXME("dibitmap should be 0 (%d)\n", info->rtfParam);
805     gfx = gfx_dib;
806   }
807   else if (RTFCheckMM (info, rtfPictAttr, rtfEmfBlip))
808   {
809     gfx = gfx_enhmetafile;
810   }
811   else
812   {
813     FIXME("%d %d\n", info->rtfMajor, info->rtfMinor);
814     goto skip_group;
815   }
816   sz.cx = sz.cy = 0;
817   /* fetch picture attributes */
818   for (;;)
819   {
820     RTFGetToken (info);
821     if (info->rtfClass == rtfEOF)
822       return;
823     if (info->rtfClass == rtfText)
824       break;
825     if (!RTFCheckCM (info, rtfControl, rtfPictAttr))
826     {
827       ERR("Expected picture attribute (%d %d)\n",
828         info->rtfClass, info->rtfMajor);
829       goto skip_group;
830     }
831     else if (RTFCheckMM (info, rtfPictAttr, rtfPicWid))
832     {
833       if (gfx == gfx_metafile) mfp.xExt = info->rtfParam;
834     }
835     else if (RTFCheckMM (info, rtfPictAttr, rtfPicHt))
836     {
837       if (gfx == gfx_metafile) mfp.yExt = info->rtfParam;
838     }
839     else if (RTFCheckMM (info, rtfPictAttr, rtfPicGoalWid))
840       sz.cx = info->rtfParam;
841     else if (RTFCheckMM (info, rtfPictAttr, rtfPicGoalHt))
842       sz.cy = info->rtfParam;
843     else
844       FIXME("Non supported attribute: %d %d %d\n", info->rtfClass, info->rtfMajor, info->rtfMinor);
845   }
846   /* fetch picture data */
847   bufsz = 1024;
848   bufidx = 0;
849   buffer = HeapAlloc(GetProcessHeap(), 0, bufsz);
850   val = info->rtfMajor;
851   for (flip = TRUE;; flip = !flip)
852   {
853     RTFGetToken (info);
854     if (info->rtfClass == rtfEOF)
855     {
856       HeapFree(GetProcessHeap(), 0, buffer);
857       return; /* Warn ?? */
858     }
859     if (RTFCheckCM(info, rtfGroup, rtfEndGroup))
860       break;
861     if (info->rtfClass != rtfText) goto skip_group;
862     if (flip)
863     {
864       if (bufidx >= bufsz &&
865           !(buffer = HeapReAlloc(GetProcessHeap(), 0, buffer, bufsz += 1024)))
866         goto skip_group;
867       buffer[bufidx++] = RTFCharToHex(val) * 16 + RTFCharToHex(info->rtfMajor);
868     }
869     else
870       val = info->rtfMajor;
871   }
872   if (flip) FIXME("wrong hex string\n");
873
874   switch (gfx)
875   {
876   case gfx_enhmetafile:
877     if ((hemf = SetEnhMetaFileBits(bufidx, buffer)))
878       ME_RTFInsertOleObject(info, hemf, NULL, &sz);
879     break;
880   case gfx_metafile:
881     if ((hemf = SetWinMetaFileBits(bufidx, buffer, NULL, &mfp)))
882         ME_RTFInsertOleObject(info, hemf, NULL, &sz);
883     break;
884   case gfx_dib:
885     {
886       BITMAPINFO* bi = (BITMAPINFO*)buffer;
887       HDC         hdc = GetDC(0);
888       unsigned    nc = bi->bmiHeader.biClrUsed;
889
890       /* not quite right, especially for bitfields type of compression */
891       if (!nc && bi->bmiHeader.biBitCount <= 8)
892         nc = 1 << bi->bmiHeader.biBitCount;
893       if ((hbmp = CreateDIBitmap(hdc, &bi->bmiHeader,
894                                  CBM_INIT, (char*)(bi + 1) + nc * sizeof(RGBQUAD),
895                                  bi, DIB_RGB_COLORS)))
896           ME_RTFInsertOleObject(info, NULL, hbmp, &sz);
897       ReleaseDC(0, hdc);
898     }
899     break;
900   default:
901     break;
902   }
903   HeapFree(GetProcessHeap(), 0, buffer);
904   RTFRouteToken (info); /* feed "}" back to router */
905   return;
906 skip_group:
907   HeapFree(GetProcessHeap(), 0, buffer);
908   RTFSkipGroup(info);
909   RTFRouteToken(info);  /* feed "}" back to router */
910 }
911
912 /* for now, lookup the \result part and use it, whatever the object */
913 static void ME_RTFReadObjectGroup(RTF_Info *info)
914 {
915   for (;;)
916   {
917     RTFGetToken (info);
918     if (info->rtfClass == rtfEOF)
919       return;
920     if (RTFCheckCM(info, rtfGroup, rtfEndGroup))
921       break;
922     if (RTFCheckCM(info, rtfGroup, rtfBeginGroup))
923     {
924       RTFGetToken (info);
925       if (info->rtfClass == rtfEOF)
926         return;
927       if (RTFCheckCMM(info, rtfControl, rtfDestination, rtfObjResult))
928       {
929         int     level = 1;
930
931         while (RTFGetToken (info) != rtfEOF)
932         {
933           if (info->rtfClass == rtfGroup)
934           {
935             if (info->rtfMajor == rtfBeginGroup) level++;
936             else if (info->rtfMajor == rtfEndGroup && --level < 0) break;
937           }
938           RTFRouteToken(info);
939         }
940       }
941       else RTFSkipGroup(info);
942       continue;
943     }
944     if (!RTFCheckCM (info, rtfControl, rtfObjAttr))
945     {
946       FIXME("Non supported attribute: %d %d %d\n", info->rtfClass, info->rtfMajor, info->rtfMinor);
947       return;
948     }
949   }
950   RTFRouteToken(info);  /* feed "}" back to router */
951 }
952
953 static void ME_RTFReadHook(RTF_Info *info) {
954   switch(info->rtfClass)
955   {
956     case rtfGroup:
957       switch(info->rtfMajor)
958       {
959         case rtfBeginGroup:
960           if (info->stackTop < maxStack) {
961             info->stack[info->stackTop].fmt = info->style->fmt;
962             info->stack[info->stackTop].codePage = info->codePage;
963             info->stack[info->stackTop].unicodeLength = info->unicodeLength;
964           }
965           info->stackTop++;
966           info->styleChanged = FALSE;
967           break;
968         case rtfEndGroup:
969         {
970           ME_Style *s;
971           RTFFlushOutputBuffer(info);
972           info->stackTop--;
973           if (info->stackTop<=0) {
974             info->rtfClass = rtfEOF;
975             return;
976           }
977           assert(info->stackTop >= 0);
978           if (info->styleChanged)
979           {
980             /* FIXME too slow ? how come ? */
981             s = ME_ApplyStyle(info->style, &info->stack[info->stackTop].fmt);
982             ME_ReleaseStyle(info->style);
983             info->style = s;
984             info->codePage = info->stack[info->stackTop].codePage;
985             info->unicodeLength = info->stack[info->stackTop].unicodeLength;
986           }
987           break;
988         }
989       }
990       break;
991     case rtfControl:
992       switch(info->rtfMajor)
993       {
994         case rtfCharAttr:
995           ME_RTFCharAttrHook(info);
996           break;
997         case rtfParAttr:
998           ME_RTFParAttrHook(info);
999           break;
1000         case rtfTblAttr:
1001           ME_RTFTblAttrHook(info);
1002           break;
1003         case rtfSpecialChar:
1004           if (info->rtfMinor == rtfCell)
1005           {
1006             RTFFlushOutputBuffer(info);
1007             ME_InsertTableCellFromCursor(info->editor, 0);
1008           }
1009       }
1010       break;
1011   }
1012 }
1013
1014 void
1015 ME_StreamInFill(ME_InStream *stream)
1016 {
1017   stream->editstream->dwError = stream->editstream->pfnCallback(stream->editstream->dwCookie,
1018                                                                 (BYTE *)stream->buffer,
1019                                                                 sizeof(stream->buffer),
1020                                                                 (LONG *)&stream->dwSize);
1021   stream->dwUsed = 0;
1022 }
1023
1024 static LRESULT ME_StreamIn(ME_TextEditor *editor, DWORD format, EDITSTREAM *stream, BOOL stripLastCR)
1025 {
1026   RTF_Info parser;
1027   ME_Style *style;
1028   int from, to, to2, nUndoMode;
1029   int nEventMask = editor->nEventMask;
1030   ME_InStream inStream;
1031   BOOL invalidRTF = FALSE;
1032
1033   TRACE("stream==%p hWnd==%p format==0x%X\n", stream, editor->hWnd, format);
1034   editor->nEventMask = 0;
1035
1036   ME_GetSelection(editor, &from, &to);
1037   if ((format & SFF_SELECTION) && (editor->mode & TM_RICHTEXT)) {
1038     style = ME_GetSelectionInsertStyle(editor);
1039
1040     ME_InternalDeleteText(editor, from, to-from);
1041   }
1042   else {
1043     style = editor->pBuffer->pDefaultStyle;
1044     ME_AddRefStyle(style);
1045     SendMessageA(editor->hWnd, EM_SETSEL, 0, 0);    
1046     ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor));
1047     from = to = 0;
1048     ME_ClearTempStyle(editor);
1049     /* FIXME restore default paragraph formatting ! */
1050   }
1051
1052
1053   /* Back up undo mode to a local variable */
1054   nUndoMode = editor->nUndoMode;
1055
1056   /* Only create an undo if SFF_SELECTION is set */
1057   if (!(format & SFF_SELECTION))
1058     editor->nUndoMode = umIgnore;
1059
1060   inStream.editstream = stream;
1061   inStream.editstream->dwError = 0;
1062   inStream.dwSize = 0;
1063   inStream.dwUsed = 0;
1064
1065   if (format & SF_RTF)
1066   {
1067     /* Check if it's really RTF, and if it is not, use plain text */
1068     ME_StreamInFill(&inStream);
1069     if (!inStream.editstream->dwError)
1070     {
1071       if ((!editor->bEmulateVersion10 && strncmp(inStream.buffer, "{\\rtf", 5) && strncmp(inStream.buffer, "{\\urtf", 6))
1072         || (editor->bEmulateVersion10 && *inStream.buffer != '{'))
1073       {
1074         invalidRTF = TRUE;
1075         inStream.editstream->dwError = -16;
1076       }
1077     }
1078   }
1079
1080   if (!invalidRTF && !inStream.editstream->dwError)
1081   {
1082     if (format & SF_RTF) {
1083       /* setup the RTF parser */
1084       memset(&parser, 0, sizeof parser);
1085       RTFSetEditStream(&parser, &inStream);
1086       parser.rtfFormat = format&(SF_TEXT|SF_RTF);
1087       parser.hwndEdit = editor->hWnd;
1088       parser.editor = editor;
1089       parser.style = style;
1090       WriterInit(&parser);
1091       RTFInit(&parser);
1092       RTFSetReadHook(&parser, ME_RTFReadHook);
1093       RTFSetDestinationCallback(&parser, rtfPict, ME_RTFReadPictGroup);
1094       RTFSetDestinationCallback(&parser, rtfObject, ME_RTFReadObjectGroup);
1095       BeginFile(&parser);
1096
1097       /* do the parsing */
1098       RTFRead(&parser);
1099       RTFFlushOutputBuffer(&parser);
1100       RTFDestroy(&parser);
1101       if (parser.lpRichEditOle)
1102         IRichEditOle_Release(parser.lpRichEditOle);
1103
1104       if (!inStream.editstream->dwError && parser.stackTop > 0)
1105         inStream.editstream->dwError = HRESULT_FROM_WIN32(ERROR_HANDLE_EOF);
1106
1107       /* Remove last line break, as mandated by tests. This is not affected by
1108          CR/LF counters, since RTF streaming presents only \para tokens, which
1109          are converted according to the standard rules: \r for 2.0, \r\n for 1.0
1110        */
1111       if (stripLastCR) {
1112         int newfrom, newto;
1113         ME_GetSelection(editor, &newfrom, &newto);
1114         if (newto > to + (editor->bEmulateVersion10 ? 1 : 0)) {
1115           WCHAR lastchar[3] = {'\0', '\0'};
1116           int linebreakSize = editor->bEmulateVersion10 ? 2 : 1;
1117
1118           ME_GetTextW(editor, lastchar, newto - linebreakSize, linebreakSize, 0);
1119           if (lastchar[0] == '\r' && (lastchar[1] == '\n' || lastchar[1] == '\0')) {
1120             ME_InternalDeleteText(editor, newto - linebreakSize, linebreakSize);
1121           }
1122         }
1123       }
1124
1125       style = parser.style;
1126     }
1127     else if (format & SF_TEXT)
1128       ME_StreamInText(editor, format, &inStream, style);
1129     else
1130       ERR("EM_STREAMIN without SF_TEXT or SF_RTF\n");
1131     ME_GetSelection(editor, &to, &to2);
1132     /* put the cursor at the top */
1133     if (!(format & SFF_SELECTION))
1134       SendMessageA(editor->hWnd, EM_SETSEL, 0, 0);
1135   }
1136
1137   /* Restore saved undo mode */
1138   editor->nUndoMode = nUndoMode;
1139
1140   /* even if we didn't add an undo, we need to commit anything on the stack */
1141   ME_CommitUndo(editor);
1142
1143   /* If SFF_SELECTION isn't set, delete any undos from before we started too */
1144   if (!(format & SFF_SELECTION))
1145     ME_EmptyUndoStack(editor);
1146
1147   ME_ReleaseStyle(style);
1148   editor->nEventMask = nEventMask;
1149   ME_UpdateRepaint(editor);
1150   if (!(format & SFF_SELECTION)) {
1151     ME_ClearTempStyle(editor);
1152   }
1153   HideCaret(editor->hWnd);
1154   ME_MoveCaret(editor);
1155   ShowCaret(editor->hWnd);
1156   ME_SendSelChange(editor);
1157   ME_SendRequestResize(editor, FALSE);
1158
1159   return 0;
1160 }
1161
1162
1163 typedef struct tagME_RTFStringStreamStruct
1164 {
1165   char *string;
1166   int pos;
1167   int length;
1168 } ME_RTFStringStreamStruct;
1169
1170 static DWORD CALLBACK ME_ReadFromRTFString(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1171 {
1172   ME_RTFStringStreamStruct *pStruct = (ME_RTFStringStreamStruct *)dwCookie;
1173   int count;
1174
1175   count = min(cb, pStruct->length - pStruct->pos);
1176   memmove(lpBuff, pStruct->string + pStruct->pos, count);
1177   pStruct->pos += count;
1178   *pcb = count;
1179   return 0;
1180 }
1181
1182 static void
1183 ME_StreamInRTFString(ME_TextEditor *editor, BOOL selection, char *string)
1184 {
1185   EDITSTREAM es;
1186   ME_RTFStringStreamStruct data;
1187
1188   data.string = string;
1189   data.length = strlen(string);
1190   data.pos = 0;
1191   es.dwCookie = (DWORD)&data;
1192   es.pfnCallback = ME_ReadFromRTFString;
1193   ME_StreamIn(editor, SF_RTF | (selection ? SFF_SELECTION : 0), &es, FALSE);
1194 }
1195
1196
1197 ME_DisplayItem *
1198 ME_FindItemAtOffset(ME_TextEditor *editor, ME_DIType nItemType, int nOffset, int *nItemOffset)
1199 {
1200   ME_DisplayItem *item = ME_FindItemFwd(editor->pBuffer->pFirst, diParagraph);
1201   int runLength;
1202   
1203   while (item && item->member.para.next_para->member.para.nCharOfs <= nOffset)
1204     item = ME_FindItemFwd(item, diParagraph);
1205
1206   if (!item)
1207     return item;
1208
1209   nOffset -= item->member.para.nCharOfs;
1210   if (nItemType == diParagraph) {
1211     if (nItemOffset)
1212       *nItemOffset = nOffset;
1213     return item;
1214   }
1215   
1216   do {
1217     item = ME_FindItemFwd(item, diRun);
1218     runLength = ME_StrLen(item->member.run.strText);
1219     if (item->member.run.nFlags & MERF_ENDPARA)
1220       runLength = item->member.run.nCR + item->member.run.nLF;
1221   } while (item && (item->member.run.nCharOfs + runLength <= nOffset));
1222   if (item) {
1223     nOffset -= item->member.run.nCharOfs;
1224
1225     /* Special case: nOffset may not point exactly at the division between the
1226        \r and the \n in 1.0 emulation. If such a case happens, it is sent
1227        into the next run, if one exists
1228      */
1229     if (   item->member.run.nFlags & MERF_ENDPARA
1230         && nOffset == item->member.run.nCR
1231         && item->member.run.nLF > 0) {
1232       ME_DisplayItem *nextItem;
1233       nextItem = ME_FindItemFwd(item, diRun);
1234       if (nextItem) {
1235         nOffset = 0;
1236         item = nextItem;
1237       }
1238     }
1239     if (nItemOffset)
1240       *nItemOffset = nOffset;
1241   }
1242   return item;
1243 }
1244
1245
1246 static int
1247 ME_FindText(ME_TextEditor *editor, DWORD flags, const CHARRANGE *chrg, const WCHAR *text, CHARRANGE *chrgText)
1248 {
1249   const int nLen = lstrlenW(text);
1250   const int nTextLen = ME_GetTextLength(editor);
1251   int nStart, nEnd;
1252   int nMin, nMax;
1253   ME_DisplayItem *item;
1254   ME_DisplayItem *para;
1255   WCHAR wLastChar = ' ';
1256
1257   TRACE("flags==0x%08x, chrg->cpMin==%d, chrg->cpMax==%d text==%s\n",
1258         flags, chrg->cpMin, chrg->cpMax, debugstr_w(text));
1259   
1260   if (flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD))
1261     FIXME("Flags 0x%08x not implemented\n",
1262         flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD));
1263
1264   nMin = chrg->cpMin;
1265   if (chrg->cpMax == -1)
1266     nMax = nTextLen;
1267   else
1268     nMax = chrg->cpMax > nTextLen ? nTextLen : chrg->cpMax;
1269   
1270   /* In 1.0 emulation, if cpMax reaches end of text, add the FR_DOWN flag */
1271   if (editor->bEmulateVersion10 && nMax == nTextLen)
1272   {
1273     flags |= FR_DOWN;
1274   }
1275
1276   /* In 1.0 emulation, cpMin must always be no greater than cpMax */
1277   if (editor->bEmulateVersion10 && nMax < nMin)
1278   {
1279     if (chrgText)
1280     {
1281       chrgText->cpMin = -1;
1282       chrgText->cpMax = -1;
1283     }
1284     return -1;
1285   }
1286
1287   /* when searching up, if cpMin < cpMax, then instead of searching
1288    * on [cpMin,cpMax], we search on [0,cpMin], otherwise, search on
1289    * [cpMax, cpMin]. The exception is when cpMax is -1, in which
1290    * case, it is always bigger than cpMin.
1291    */
1292   if (!editor->bEmulateVersion10 && !(flags & FR_DOWN))
1293   {
1294     int nSwap = nMax;
1295
1296     nMax = nMin > nTextLen ? nTextLen : nMin;
1297     if (nMin < nSwap || chrg->cpMax == -1)
1298       nMin = 0;
1299     else
1300       nMin = nSwap;
1301   }
1302
1303   if (!nLen || nMin < 0 || nMax < 0 || nMax < nMin)
1304   {
1305     if (chrgText)
1306       chrgText->cpMin = chrgText->cpMax = -1;
1307     return -1;
1308   }
1309  
1310   if (flags & FR_DOWN) /* Forward search */
1311   {
1312     /* If possible, find the character before where the search starts */
1313     if ((flags & FR_WHOLEWORD) && nMin)
1314     {
1315       nStart = nMin - 1;
1316       item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
1317       if (!item)
1318       {
1319         if (chrgText)
1320           chrgText->cpMin = chrgText->cpMax = -1;
1321         return -1;
1322       }
1323       wLastChar = item->member.run.strText->szData[nStart];
1324     }
1325
1326     nStart = nMin;
1327     item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
1328     if (!item)
1329     {
1330       if (chrgText)
1331         chrgText->cpMin = chrgText->cpMax = -1;
1332       return -1;
1333     }
1334
1335     para = ME_GetParagraph(item);
1336     while (item
1337            && para->member.para.nCharOfs + item->member.run.nCharOfs + nStart + nLen <= nMax)
1338     {
1339       ME_DisplayItem *pCurItem = item;
1340       int nCurStart = nStart;
1341       int nMatched = 0;
1342     
1343       while (pCurItem && ME_CharCompare(pCurItem->member.run.strText->szData[nCurStart + nMatched], text[nMatched], (flags & FR_MATCHCASE)))
1344       {
1345         if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
1346           break;
1347
1348         nMatched++;
1349         if (nMatched == nLen)
1350         {
1351           ME_DisplayItem *pNextItem = pCurItem;
1352           int nNextStart = nCurStart;
1353           WCHAR wNextChar;
1354
1355           /* Check to see if next character is a whitespace */
1356           if (flags & FR_WHOLEWORD)
1357           {
1358             if (nCurStart + nMatched == ME_StrLen(pCurItem->member.run.strText))
1359             {
1360               pNextItem = ME_FindItemFwd(pCurItem, diRun);
1361               nNextStart = -nMatched;
1362             }
1363
1364             if (pNextItem)
1365               wNextChar = pNextItem->member.run.strText->szData[nNextStart + nMatched];
1366             else
1367               wNextChar = ' ';
1368
1369             if (isalnumW(wNextChar))
1370               break;
1371           }
1372
1373           nStart += para->member.para.nCharOfs + item->member.run.nCharOfs;
1374           if (chrgText)
1375           {
1376             chrgText->cpMin = nStart;
1377             chrgText->cpMax = nStart + nLen;
1378           }
1379           TRACE("found at %d-%d\n", nStart, nStart + nLen);
1380           return nStart;
1381         }
1382         if (nCurStart + nMatched == ME_StrLen(pCurItem->member.run.strText))
1383         {
1384           pCurItem = ME_FindItemFwd(pCurItem, diRun);
1385           para = ME_GetParagraph(pCurItem);
1386           nCurStart = -nMatched;
1387         }
1388       }
1389       if (pCurItem)
1390         wLastChar = pCurItem->member.run.strText->szData[nCurStart + nMatched];
1391       else
1392         wLastChar = ' ';
1393
1394       nStart++;
1395       if (nStart == ME_StrLen(item->member.run.strText))
1396       {
1397         item = ME_FindItemFwd(item, diRun);
1398         para = ME_GetParagraph(item);
1399         nStart = 0;
1400       }
1401     }
1402   }
1403   else /* Backward search */
1404   {
1405     /* If possible, find the character after where the search ends */
1406     if ((flags & FR_WHOLEWORD) && nMax < nTextLen - 1)
1407     {
1408       nEnd = nMax + 1;
1409       item = ME_FindItemAtOffset(editor, diRun, nEnd, &nEnd);
1410       if (!item)
1411       {
1412         if (chrgText)
1413           chrgText->cpMin = chrgText->cpMax = -1;
1414         return -1;
1415       }
1416       wLastChar = item->member.run.strText->szData[nEnd];
1417     }
1418
1419     nEnd = nMax;
1420     item = ME_FindItemAtOffset(editor, diRun, nEnd, &nEnd);
1421     if (!item)
1422     {
1423       if (chrgText)
1424         chrgText->cpMin = chrgText->cpMax = -1;
1425       return -1;
1426     }
1427     
1428     para = ME_GetParagraph(item);
1429     
1430     while (item
1431            && para->member.para.nCharOfs + item->member.run.nCharOfs + nEnd - nLen >= nMin)
1432     {
1433       ME_DisplayItem *pCurItem = item;
1434       int nCurEnd = nEnd;
1435       int nMatched = 0;
1436       
1437       if (nCurEnd - nMatched == 0)
1438       {
1439         pCurItem = ME_FindItemBack(pCurItem, diRun);
1440         para = ME_GetParagraph(pCurItem);
1441         nCurEnd = ME_StrLen(pCurItem->member.run.strText) + nMatched;
1442       }
1443       
1444       while (pCurItem && ME_CharCompare(pCurItem->member.run.strText->szData[nCurEnd - nMatched - 1], text[nLen - nMatched - 1], (flags & FR_MATCHCASE)))
1445       {
1446         if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
1447           break;
1448
1449         nMatched++;
1450         if (nMatched == nLen)
1451         {
1452           ME_DisplayItem *pPrevItem = pCurItem;
1453           int nPrevEnd = nCurEnd;
1454           WCHAR wPrevChar;
1455
1456           /* Check to see if previous character is a whitespace */
1457           if (flags & FR_WHOLEWORD)
1458           {
1459             if (nPrevEnd - nMatched == 0)
1460             {
1461               pPrevItem = ME_FindItemBack(pCurItem, diRun);
1462               if (pPrevItem)
1463                 nPrevEnd = ME_StrLen(pPrevItem->member.run.strText) + nMatched;
1464             }
1465
1466             if (pPrevItem)
1467               wPrevChar = pPrevItem->member.run.strText->szData[nPrevEnd - nMatched - 1];
1468             else
1469               wPrevChar = ' ';
1470
1471             if (isalnumW(wPrevChar))
1472               break;
1473           }
1474
1475           nStart = para->member.para.nCharOfs + pCurItem->member.run.nCharOfs + nCurEnd - nMatched;
1476           if (chrgText)
1477           {
1478             chrgText->cpMin = nStart;
1479             chrgText->cpMax = nStart + nLen;
1480           }
1481           TRACE("found at %d-%d\n", nStart, nStart + nLen);
1482           return nStart;
1483         }
1484         if (nCurEnd - nMatched == 0)
1485         {
1486           pCurItem = ME_FindItemBack(pCurItem, diRun);
1487           /* Don't care about pCurItem becoming NULL here; it's already taken
1488            * care of in the exterior loop condition */
1489           para = ME_GetParagraph(pCurItem);
1490           nCurEnd = ME_StrLen(pCurItem->member.run.strText) + nMatched;
1491         }
1492       }
1493       if (pCurItem)
1494         wLastChar = pCurItem->member.run.strText->szData[nCurEnd - nMatched - 1];
1495       else
1496         wLastChar = ' ';
1497
1498       nEnd--;
1499       if (nEnd < 0)
1500       {
1501         item = ME_FindItemBack(item, diRun);
1502         para = ME_GetParagraph(item);
1503         nEnd = ME_StrLen(item->member.run.strText);
1504       }
1505     }
1506   }
1507   TRACE("not found\n");
1508   if (chrgText)
1509     chrgText->cpMin = chrgText->cpMax = -1;
1510   return -1;
1511 }
1512
1513 /* helper to send a msg filter notification */
1514 static BOOL
1515 ME_FilterEvent(ME_TextEditor *editor, UINT msg, WPARAM* wParam, LPARAM* lParam)
1516 {
1517     MSGFILTER msgf;
1518
1519     msgf.nmhdr.hwndFrom = editor->hWnd;
1520     msgf.nmhdr.idFrom = GetWindowLongW(editor->hWnd, GWLP_ID);
1521     msgf.nmhdr.code = EN_MSGFILTER;
1522     msgf.msg = msg;
1523
1524     msgf.wParam = *wParam;
1525     msgf.lParam = *lParam;
1526     if (SendMessageW(GetParent(editor->hWnd), WM_NOTIFY, msgf.nmhdr.idFrom, (LPARAM)&msgf))
1527         return FALSE;
1528     *wParam = msgf.wParam;
1529     *lParam = msgf.lParam;
1530     msgf.wParam = *wParam;
1531
1532     return TRUE;
1533 }
1534
1535 static BOOL
1536 ME_KeyDown(ME_TextEditor *editor, WORD nKey)
1537 {
1538   BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
1539   BOOL shift_is_down = GetKeyState(VK_SHIFT) & 0x8000;
1540
1541   if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey != VK_MENU)
1542       editor->nSelectionType = stPosition;
1543
1544   switch (nKey)
1545   {
1546     case VK_LEFT:
1547     case VK_RIGHT:
1548     case VK_HOME:
1549     case VK_END:
1550         editor->nUDArrowX = -1;
1551         /* fall through */
1552     case VK_UP:
1553     case VK_DOWN:
1554     case VK_PRIOR:
1555     case VK_NEXT:
1556       ME_CommitUndo(editor); /* End coalesced undos for typed characters */
1557       ME_ArrowKey(editor, nKey, shift_is_down, ctrl_is_down);
1558       return TRUE;
1559     case VK_BACK:
1560     case VK_DELETE:
1561       editor->nUDArrowX = -1;
1562       /* FIXME backspace and delete aren't the same, they act different wrt paragraph style of the merged paragraph */
1563       if (GetWindowLongW(editor->hWnd, GWL_STYLE) & ES_READONLY)
1564         return FALSE;
1565       if (ME_IsSelection(editor))
1566       {
1567         ME_DeleteSelection(editor);
1568         ME_CommitUndo(editor);
1569       }
1570       else if (nKey == VK_DELETE)
1571       {
1572         /* Delete stops group typing.
1573          * (See MSDN remarks on EM_STOPGROUPTYPING message) */
1574         ME_DeleteTextAtCursor(editor, 1, 1);
1575         ME_CommitUndo(editor);
1576       }
1577       else if (ME_ArrowKey(editor, VK_LEFT, FALSE, FALSE))
1578       {
1579           /* Backspace can be grouped for a single undo */
1580           ME_ContinueCoalescingTransaction(editor);
1581           ME_DeleteTextAtCursor(editor, 1, 1);
1582           ME_CommitCoalescingUndo(editor);
1583       }
1584       else
1585         return TRUE;
1586       ME_UpdateSelectionLinkAttribute(editor);
1587       ME_UpdateRepaint(editor);
1588       ME_SendRequestResize(editor, FALSE);
1589       return TRUE;
1590
1591     default:
1592       if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey && nKey != VK_MENU)
1593           editor->nUDArrowX = -1;
1594       if (ctrl_is_down)
1595       {
1596         if (nKey == 'W')
1597         {
1598           CHARFORMAT2W chf;
1599           char buf[2048];
1600           chf.cbSize = sizeof(chf);
1601           
1602           ME_GetSelectionCharFormat(editor, &chf);
1603           ME_DumpStyleToBuf(&chf, buf);
1604           MessageBoxA(NULL, buf, "Style dump", MB_OK);
1605         }
1606         if (nKey == 'Q')
1607         {
1608           ME_CheckCharOffsets(editor);
1609         }
1610       }
1611   }
1612   return FALSE;
1613 }
1614
1615 /* Process the message and calculate the new click count.
1616  *
1617  * returns: The click count if it is mouse down event, else returns 0. */
1618 static int ME_CalculateClickCount(HWND hWnd, UINT msg, WPARAM wParam,
1619                                   LPARAM lParam)
1620 {
1621     static int clickNum = 0;
1622     if (msg < WM_MOUSEFIRST || msg > WM_MOUSELAST)
1623         return 0;
1624
1625     if ((msg == WM_LBUTTONDBLCLK) ||
1626         (msg == WM_RBUTTONDBLCLK) ||
1627         (msg == WM_MBUTTONDBLCLK) ||
1628         (msg == WM_XBUTTONDBLCLK))
1629     {
1630         msg -= (WM_LBUTTONDBLCLK - WM_LBUTTONDOWN);
1631     }
1632
1633     if ((msg == WM_LBUTTONDOWN) ||
1634         (msg == WM_RBUTTONDOWN) ||
1635         (msg == WM_MBUTTONDOWN) ||
1636         (msg == WM_XBUTTONDOWN))
1637     {
1638         static MSG prevClickMsg;
1639         MSG clickMsg;
1640         clickMsg.hwnd = hWnd;
1641         clickMsg.message = msg;
1642         clickMsg.wParam = wParam;
1643         clickMsg.lParam = lParam;
1644         clickMsg.time = GetMessageTime();
1645         clickMsg.pt.x = (short)LOWORD(lParam);
1646         clickMsg.pt.y = (short)HIWORD(lParam);
1647         if ((clickNum != 0) &&
1648             (clickMsg.message == prevClickMsg.message) &&
1649             (clickMsg.hwnd == prevClickMsg.hwnd) &&
1650             (clickMsg.wParam == prevClickMsg.wParam) &&
1651             (clickMsg.time - prevClickMsg.time < GetDoubleClickTime()) &&
1652             (abs(clickMsg.pt.x - prevClickMsg.pt.x) < GetSystemMetrics(SM_CXDOUBLECLK)/2) &&
1653             (abs(clickMsg.pt.y - prevClickMsg.pt.y) < GetSystemMetrics(SM_CYDOUBLECLK)/2))
1654         {
1655             clickNum++;
1656         } else {
1657             clickNum = 1;
1658         }
1659         prevClickMsg = clickMsg;
1660     } else {
1661         return 0;
1662     }
1663     return clickNum;
1664 }
1665
1666 static BOOL ME_SetCursor(ME_TextEditor *editor, int x)
1667 {
1668   if ((GetWindowLongW(editor->hWnd, GWL_STYLE) & ES_SELECTIONBAR) &&
1669       (x < editor->selofs ||
1670        (editor->nSelectionType == stLine && GetCapture() == editor->hWnd)))
1671   {
1672       SetCursor(hLeft);
1673       return TRUE;
1674   }
1675   return FALSE;
1676 }
1677
1678 static BOOL ME_ShowContextMenu(ME_TextEditor *editor, int x, int y)
1679 {
1680   CHARRANGE selrange;
1681   HMENU menu;
1682   int seltype = 0;
1683   if(!editor->lpOleCallback)
1684     return FALSE;
1685   ME_GetSelection(editor, &selrange.cpMin, &selrange.cpMax);
1686   if(selrange.cpMin == selrange.cpMax)
1687     seltype |= SEL_EMPTY;
1688   else
1689   {
1690     /* FIXME: Handle objects */
1691     seltype |= SEL_TEXT;
1692     if(selrange.cpMax-selrange.cpMin > 1)
1693       seltype |= SEL_MULTICHAR;
1694   }
1695   if(SUCCEEDED(IRichEditOleCallback_GetContextMenu(editor->lpOleCallback, seltype, NULL, &selrange, &menu)))
1696   {
1697     TrackPopupMenu(menu, TPM_LEFTALIGN | TPM_RIGHTBUTTON, x, y, 0, GetParent(editor->hWnd), NULL);
1698     DestroyMenu(menu);
1699   }
1700   return TRUE;
1701 }
1702
1703 ME_TextEditor *ME_MakeEditor(HWND hWnd) {
1704   ME_TextEditor *ed = ALLOC_OBJ(ME_TextEditor);
1705   int i;
1706   ed->hWnd = hWnd;
1707   ed->bEmulateVersion10 = FALSE;
1708   ed->pBuffer = ME_MakeText();
1709   ed->nZoomNumerator = ed->nZoomDenominator = 0;
1710   ME_MakeFirstParagraph(ed);
1711   /* The four cursors are for:
1712    * 0 - The position where the caret is shown
1713    * 1 - The anchored end of the selection (for normal selection)
1714    * 2 & 3 - The anchored start and end respectively for word, line,
1715    * or paragraph selection.
1716    */
1717   ed->nCursors = 4;
1718   ed->pCursors = ALLOC_N_OBJ(ME_Cursor, ed->nCursors);
1719   ed->pCursors[0].pRun = ME_FindItemFwd(ed->pBuffer->pFirst, diRun);
1720   ed->pCursors[0].nOffset = 0;
1721   ed->pCursors[1].pRun = ME_FindItemFwd(ed->pBuffer->pFirst, diRun);
1722   ed->pCursors[1].nOffset = 0;
1723   ed->pCursors[2] = ed->pCursors[0];
1724   ed->pCursors[3] = ed->pCursors[1];
1725   ed->nLastTotalLength = ed->nTotalLength = 0;
1726   ed->nHeight = 0;
1727   ed->nUDArrowX = -1;
1728   ed->nSequence = 0;
1729   ed->rgbBackColor = -1;
1730   ed->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
1731   ed->bCaretAtEnd = FALSE;
1732   ed->nEventMask = 0;
1733   ed->nModifyStep = 0;
1734   ed->nTextLimit = TEXT_LIMIT_DEFAULT;
1735   ed->pUndoStack = ed->pRedoStack = ed->pUndoStackBottom = NULL;
1736   ed->nUndoStackSize = 0;
1737   ed->nUndoLimit = STACK_SIZE_DEFAULT;
1738   ed->nUndoMode = umAddToUndo;
1739   ed->nParagraphs = 1;
1740   ed->nLastSelStart = ed->nLastSelEnd = 0;
1741   ed->pLastSelStartPara = ed->pLastSelEndPara = ME_FindItemFwd(ed->pBuffer->pFirst, diParagraph);
1742   ed->bRedraw = TRUE;
1743   ed->bWordWrap = (GetWindowLongW(hWnd, GWL_STYLE) & WS_HSCROLL) ? FALSE : TRUE;
1744   ed->bHideSelection = FALSE;
1745   ed->nInvalidOfs = -1;
1746   ed->pfnWordBreak = NULL;
1747   ed->lpOleCallback = NULL;
1748   ed->mode = TM_RICHTEXT | TM_MULTILEVELUNDO | TM_MULTICODEPAGE;
1749   ed->AutoURLDetect_bEnable = FALSE;
1750   ed->bHaveFocus = FALSE;
1751   for (i=0; i<HFONT_CACHE_SIZE; i++)
1752   {
1753     ed->pFontCache[i].nRefs = 0;
1754     ed->pFontCache[i].nAge = 0;
1755     ed->pFontCache[i].hFont = NULL;
1756   }
1757   
1758   ME_CheckCharOffsets(ed);
1759   if (GetWindowLongW(hWnd, GWL_STYLE) & ES_SELECTIONBAR)
1760     ed->selofs = SELECTIONBAR_WIDTH;
1761   else
1762     ed->selofs = 0;
1763   ed->nSelectionType = stPosition;
1764
1765   if (GetWindowLongW(hWnd, GWL_STYLE) & ES_PASSWORD)
1766     ed->cPasswordMask = '*';
1767   else
1768     ed->cPasswordMask = 0;
1769   
1770   ed->notified_cr.cpMin = ed->notified_cr.cpMax = 0;
1771
1772   return ed;
1773 }
1774
1775 typedef struct tagME_GlobalDestStruct
1776 {
1777   HGLOBAL hData;
1778   int nLength;
1779 } ME_GlobalDestStruct;
1780
1781 static DWORD CALLBACK ME_ReadFromHGLOBALUnicode(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1782 {
1783   ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
1784   int i;
1785   WORD *pSrc, *pDest;
1786   
1787   cb = cb >> 1;
1788   pDest = (WORD *)lpBuff;
1789   pSrc = (WORD *)GlobalLock(pData->hData);
1790   for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
1791     pDest[i] = pSrc[pData->nLength+i];
1792   }    
1793   pData->nLength += i;
1794   *pcb = 2*i;
1795   GlobalUnlock(pData->hData);
1796   return 0;
1797 }
1798
1799 static DWORD CALLBACK ME_ReadFromHGLOBALRTF(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1800 {
1801   ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
1802   int i;
1803   BYTE *pSrc, *pDest;
1804   
1805   pDest = lpBuff;
1806   pSrc = (BYTE *)GlobalLock(pData->hData);
1807   for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
1808     pDest[i] = pSrc[pData->nLength+i];
1809   }    
1810   pData->nLength += i;
1811   *pcb = i;
1812   GlobalUnlock(pData->hData);
1813   return 0;
1814 }
1815
1816
1817 void ME_DestroyEditor(ME_TextEditor *editor)
1818 {
1819   ME_DisplayItem *pFirst = editor->pBuffer->pFirst;
1820   ME_DisplayItem *p = pFirst, *pNext = NULL;
1821   int i;
1822
1823   ME_ClearTempStyle(editor);
1824   ME_EmptyUndoStack(editor);
1825   while(p) {
1826     pNext = p->next;
1827     ME_DestroyDisplayItem(p);
1828     p = pNext;
1829   }
1830   ME_ReleaseStyle(editor->pBuffer->pDefaultStyle);
1831   for (i=0; i<HFONT_CACHE_SIZE; i++)
1832   {
1833     if (editor->pFontCache[i].hFont)
1834       DeleteObject(editor->pFontCache[i].hFont);
1835   }
1836   if (editor->rgbBackColor != -1)
1837     DeleteObject(editor->hbrBackground);
1838   if(editor->lpOleCallback)
1839     IUnknown_Release(editor->lpOleCallback);
1840
1841   FREE_OBJ(editor->pBuffer);
1842   FREE_OBJ(editor->pCursors);
1843
1844   FREE_OBJ(editor);
1845 }
1846
1847 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
1848 {
1849     TRACE("\n");
1850     switch (fdwReason)
1851     {
1852     case DLL_PROCESS_ATTACH:
1853       DisableThreadLibraryCalls(hinstDLL);
1854       me_heap = HeapCreate (0, 0x10000, 0);
1855       if (!ME_RegisterEditorClass(hinstDLL)) return FALSE;
1856       hLeft = LoadCursorW(hinstDLL, MAKEINTRESOURCEW(OCR_REVERSE));
1857       LookupInit();
1858       break;
1859
1860     case DLL_PROCESS_DETACH:
1861       UnregisterClassW(RichEdit20W, 0);
1862       UnregisterClassW(RichEdit50W, 0);
1863       UnregisterClassA("RichEdit20A", 0);
1864       UnregisterClassA("RichEdit50A", 0);
1865       if (ME_ListBoxRegistered)
1866           UnregisterClassW(REListBox20W, 0);
1867       if (ME_ComboBoxRegistered)
1868           UnregisterClassW(REComboBox20W, 0);
1869       LookupCleanup();
1870       HeapDestroy (me_heap);
1871       me_heap = NULL;
1872       break;
1873     }
1874     return TRUE;
1875 }
1876
1877
1878 #define UNSUPPORTED_MSG(e) \
1879   case e: \
1880     FIXME(#e ": stub\n"); \
1881     return DefWindowProcW(hWnd, msg, wParam, lParam);
1882
1883 static const char * const edit_messages[] = {
1884   "EM_GETSEL",
1885   "EM_SETSEL",
1886   "EM_GETRECT",
1887   "EM_SETRECT",
1888   "EM_SETRECTNP",
1889   "EM_SCROLL",
1890   "EM_LINESCROLL",
1891   "EM_SCROLLCARET",
1892   "EM_GETMODIFY",
1893   "EM_SETMODIFY",
1894   "EM_GETLINECOUNT",
1895   "EM_LINEINDEX",
1896   "EM_SETHANDLE",
1897   "EM_GETHANDLE",
1898   "EM_GETTHUMB",
1899   "EM_UNKNOWN_BF",
1900   "EM_UNKNOWN_C0",
1901   "EM_LINELENGTH",
1902   "EM_REPLACESEL",
1903   "EM_UNKNOWN_C3",
1904   "EM_GETLINE",
1905   "EM_LIMITTEXT",
1906   "EM_CANUNDO",
1907   "EM_UNDO",
1908   "EM_FMTLINES",
1909   "EM_LINEFROMCHAR",
1910   "EM_UNKNOWN_CA",
1911   "EM_SETTABSTOPS",
1912   "EM_SETPASSWORDCHAR",
1913   "EM_EMPTYUNDOBUFFER",
1914   "EM_GETFIRSTVISIBLELINE",
1915   "EM_SETREADONLY",
1916   "EM_SETWORDBREAKPROC",
1917   "EM_GETWORDBREAKPROC",
1918   "EM_GETPASSWORDCHAR",
1919   "EM_SETMARGINS",
1920   "EM_GETMARGINS",
1921   "EM_GETLIMITTEXT",
1922   "EM_POSFROMCHAR",
1923   "EM_CHARFROMPOS"
1924 };
1925
1926 static const char * const richedit_messages[] = {
1927   "EM_CANPASTE",
1928   "EM_DISPLAYBAND",
1929   "EM_EXGETSEL",
1930   "EM_EXLIMITTEXT",
1931   "EM_EXLINEFROMCHAR",
1932   "EM_EXSETSEL",
1933   "EM_FINDTEXT",
1934   "EM_FORMATRANGE",
1935   "EM_GETCHARFORMAT",
1936   "EM_GETEVENTMASK",
1937   "EM_GETOLEINTERFACE",
1938   "EM_GETPARAFORMAT",
1939   "EM_GETSELTEXT",
1940   "EM_HIDESELECTION", 
1941   "EM_PASTESPECIAL",
1942   "EM_REQUESTRESIZE",
1943   "EM_SELECTIONTYPE",
1944   "EM_SETBKGNDCOLOR",
1945   "EM_SETCHARFORMAT",
1946   "EM_SETEVENTMASK",
1947   "EM_SETOLECALLBACK",
1948   "EM_SETPARAFORMAT",
1949   "EM_SETTARGETDEVICE",
1950   "EM_STREAMIN",
1951   "EM_STREAMOUT",
1952   "EM_GETTEXTRANGE",
1953   "EM_FINDWORDBREAK",
1954   "EM_SETOPTIONS",
1955   "EM_GETOPTIONS",
1956   "EM_FINDTEXTEX",
1957   "EM_GETWORDBREAKPROCEX",
1958   "EM_SETWORDBREAKPROCEX",
1959   "EM_SETUNDOLIMIT",
1960   "EM_UNKNOWN_USER_83",
1961   "EM_REDO",
1962   "EM_CANREDO",
1963   "EM_GETUNDONAME",
1964   "EM_GETREDONAME",
1965   "EM_STOPGROUPTYPING",
1966   "EM_SETTEXTMODE",
1967   "EM_GETTEXTMODE",
1968   "EM_AUTOURLDETECT",
1969   "EM_GETAUTOURLDETECT",
1970   "EM_SETPALETTE",
1971   "EM_GETTEXTEX",
1972   "EM_GETTEXTLENGTHEX",
1973   "EM_SHOWSCROLLBAR",
1974   "EM_SETTEXTEX",
1975   "EM_UNKNOWN_USER_98",
1976   "EM_UNKNOWN_USER_99",
1977   "EM_SETPUNCTUATION",
1978   "EM_GETPUNCTUATION",
1979   "EM_SETWORDWRAPMODE",
1980   "EM_GETWORDWRAPMODE",
1981   "EM_SETIMECOLOR",
1982   "EM_GETIMECOLOR",
1983   "EM_SETIMEOPTIONS",
1984   "EM_GETIMEOPTIONS",
1985   "EM_CONVPOSITION",
1986   "EM_UNKNOWN_USER_109",
1987   "EM_UNKNOWN_USER_110",
1988   "EM_UNKNOWN_USER_111",
1989   "EM_UNKNOWN_USER_112",
1990   "EM_UNKNOWN_USER_113",
1991   "EM_UNKNOWN_USER_114",
1992   "EM_UNKNOWN_USER_115",
1993   "EM_UNKNOWN_USER_116",
1994   "EM_UNKNOWN_USER_117",
1995   "EM_UNKNOWN_USER_118",
1996   "EM_UNKNOWN_USER_119",
1997   "EM_SETLANGOPTIONS",
1998   "EM_GETLANGOPTIONS",
1999   "EM_GETIMECOMPMODE",
2000   "EM_FINDTEXTW",
2001   "EM_FINDTEXTEXW",
2002   "EM_RECONVERSION",
2003   "EM_SETIMEMODEBIAS",
2004   "EM_GETIMEMODEBIAS"
2005 };
2006
2007 static const char *
2008 get_msg_name(UINT msg)
2009 {
2010   if (msg >= EM_GETSEL && msg <= EM_CHARFROMPOS)
2011     return edit_messages[msg - EM_GETSEL];
2012   if (msg >= EM_CANPASTE && msg <= EM_GETIMEMODEBIAS)
2013     return richedit_messages[msg - EM_CANPASTE];
2014   return "";
2015 }
2016
2017 static LRESULT RichEditWndProc_common(HWND hWnd, UINT msg, WPARAM wParam,
2018                                       LPARAM lParam, BOOL unicode)
2019 {
2020   ME_TextEditor *editor = (ME_TextEditor *)GetWindowLongPtrW(hWnd, 0);
2021   
2022   TRACE("hwnd %p msg %04x (%s) %lx %lx, unicode %d\n",
2023         hWnd, msg, get_msg_name(msg), wParam, lParam, unicode);
2024   
2025   if (!editor && msg != WM_NCCREATE && msg != WM_NCDESTROY) {
2026     ERR("called with invalid hWnd %p - application bug?\n", hWnd);
2027     return 0; 
2028   }
2029
2030   switch(msg) {
2031   
2032   UNSUPPORTED_MSG(EM_DISPLAYBAND)
2033   UNSUPPORTED_MSG(EM_FINDWORDBREAK)
2034   UNSUPPORTED_MSG(EM_FMTLINES)
2035   UNSUPPORTED_MSG(EM_FORMATRANGE)
2036   UNSUPPORTED_MSG(EM_GETBIDIOPTIONS)
2037   UNSUPPORTED_MSG(EM_GETEDITSTYLE)
2038   UNSUPPORTED_MSG(EM_GETIMECOMPMODE)
2039   /* UNSUPPORTED_MSG(EM_GETIMESTATUS) missing in Wine headers */
2040   UNSUPPORTED_MSG(EM_GETLANGOPTIONS)
2041   /* UNSUPPORTED_MSG(EM_GETOLEINTERFACE) separate stub */
2042   UNSUPPORTED_MSG(EM_GETREDONAME)
2043   UNSUPPORTED_MSG(EM_GETTEXTMODE)
2044   UNSUPPORTED_MSG(EM_GETTYPOGRAPHYOPTIONS)
2045   UNSUPPORTED_MSG(EM_GETUNDONAME)
2046   UNSUPPORTED_MSG(EM_GETWORDBREAKPROCEX)
2047   UNSUPPORTED_MSG(EM_PASTESPECIAL)
2048   UNSUPPORTED_MSG(EM_SELECTIONTYPE)
2049   UNSUPPORTED_MSG(EM_SETBIDIOPTIONS)
2050   UNSUPPORTED_MSG(EM_SETEDITSTYLE)
2051   UNSUPPORTED_MSG(EM_SETFONTSIZE)
2052   UNSUPPORTED_MSG(EM_SETLANGOPTIONS)
2053   UNSUPPORTED_MSG(EM_SETPALETTE)
2054   UNSUPPORTED_MSG(EM_SETTABSTOPS)
2055   UNSUPPORTED_MSG(EM_SETTYPOGRAPHYOPTIONS)
2056   UNSUPPORTED_MSG(EM_SETWORDBREAKPROCEX)
2057   UNSUPPORTED_MSG(WM_STYLECHANGING)
2058   UNSUPPORTED_MSG(WM_STYLECHANGED)
2059 /*  UNSUPPORTED_MSG(WM_UNICHAR) FIXME missing in Wine headers */
2060     
2061 /* Messages specific to Richedit controls */
2062   
2063   case EM_STREAMIN:
2064    return ME_StreamIn(editor, wParam, (EDITSTREAM*)lParam, TRUE);
2065   case EM_STREAMOUT:
2066    return ME_StreamOut(editor, wParam, (EDITSTREAM *)lParam);
2067   case WM_GETDLGCODE:
2068   {
2069     UINT code = DLGC_WANTCHARS|DLGC_WANTARROWS;
2070     if(lParam && (((LPMSG)lParam)->message == WM_KEYDOWN))
2071     {
2072       int vk = (int)((LPMSG)lParam)->wParam;
2073       /* if style says we want return key */
2074       if((vk == VK_RETURN) && (GetWindowLongW(hWnd, GWL_STYLE) & ES_WANTRETURN))
2075       {
2076         code |= DLGC_WANTMESSAGE;
2077       }
2078       /* we always handle ctrl-tab */
2079       if((vk == VK_TAB) && (GetKeyState(VK_CONTROL) & 0x8000))
2080       {
2081         code |= DLGC_WANTMESSAGE;
2082       }
2083     }
2084     return code;
2085   }
2086   case WM_NCCREATE:
2087   {
2088     CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
2089     TRACE("WM_NCCREATE: style 0x%08x\n", pcs->style);
2090     editor = ME_MakeEditor(hWnd);
2091     SetWindowLongPtrW(hWnd, 0, (LONG_PTR)editor);
2092     return TRUE;
2093   }
2094   case EM_EMPTYUNDOBUFFER:
2095     ME_EmptyUndoStack(editor);
2096     return 0;
2097   case EM_GETSEL:
2098   {
2099     /* Note: wParam/lParam can be NULL */
2100     UINT from, to;
2101     PUINT pfrom = wParam ? (PUINT)wParam : &from;
2102     PUINT pto = lParam ? (PUINT)lParam : &to;
2103     ME_GetSelection(editor, (int *)pfrom, (int *)pto);
2104     if ((*pfrom|*pto) & 0xFFFF0000)
2105       return -1;
2106     return MAKELONG(*pfrom,*pto);
2107   }
2108   case EM_EXGETSEL:
2109   {
2110     CHARRANGE *pRange = (CHARRANGE *)lParam;
2111     ME_GetSelection(editor, &pRange->cpMin, &pRange->cpMax);
2112     TRACE("EM_EXGETSEL = (%d,%d)\n", pRange->cpMin, pRange->cpMax);
2113     return 0;
2114   }
2115   case EM_SETUNDOLIMIT:
2116   {
2117     if ((int)wParam < 0)
2118       editor->nUndoLimit = STACK_SIZE_DEFAULT;
2119     else
2120       editor->nUndoLimit = min(wParam, STACK_SIZE_MAX);
2121     /* Setting a max stack size keeps wine from getting killed 
2122       for hogging memory. Windows allocates all this memory at once, so
2123       no program would realistically set a value above our maximum. */
2124     return editor->nUndoLimit;
2125   }
2126   case EM_CANUNDO:
2127     return editor->pUndoStack != NULL;
2128   case EM_CANREDO:
2129     return editor->pRedoStack != NULL;
2130   case WM_UNDO: /* FIXME: actually not the same */
2131   case EM_UNDO:
2132     return ME_Undo(editor);
2133   case EM_REDO:
2134     return ME_Redo(editor);
2135   case EM_GETOPTIONS:
2136   {
2137     /* these flags are equivalent to the ES_* counterparts */
2138     DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
2139                  ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN;
2140     DWORD settings = GetWindowLongW(hWnd, GWL_STYLE) & mask;
2141
2142     return settings;
2143   }
2144   case EM_SETOPTIONS:
2145   {
2146     /* these flags are equivalent to ES_* counterparts                      
2147      * ECO_READONLY is already implemented in the code, only requires 
2148      * setting the bit to work                                        
2149      */
2150     DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
2151                  ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN | ECO_SELECTIONBAR;
2152     DWORD raw = GetWindowLongW(hWnd, GWL_STYLE);
2153     DWORD settings = mask & raw;
2154
2155     switch(wParam)
2156     {
2157       case ECOOP_SET:
2158         settings = lParam;
2159         break;
2160       case ECOOP_OR:
2161         settings |= lParam;
2162         break;
2163       case ECOOP_AND:
2164         settings &= lParam;
2165         break;
2166       case ECOOP_XOR:
2167         settings ^= lParam;
2168     }
2169     SetWindowLongW(hWnd, GWL_STYLE, (raw & ~mask) | (settings & mask));
2170
2171     if (settings & ECO_AUTOWORDSELECTION)
2172       FIXME("ECO_AUTOWORDSELECTION not implemented yet!\n");
2173     if (settings & ECO_SELECTIONBAR)
2174         editor->selofs = SELECTIONBAR_WIDTH;
2175     else
2176         editor->selofs = 0;
2177     ME_WrapMarkedParagraphs(editor);
2178
2179     if (settings & ECO_VERTICAL)
2180       FIXME("ECO_VERTICAL not implemented yet!\n");
2181     if (settings & ECO_AUTOHSCROLL)
2182       FIXME("ECO_AUTOHSCROLL not implemented yet!\n");
2183     if (settings & ECO_AUTOVSCROLL)
2184       FIXME("ECO_AUTOVSCROLL not implemented yet!\n");
2185     if (settings & ECO_NOHIDESEL)
2186       FIXME("ECO_NOHIDESEL not implemented yet!\n");
2187     if (settings & ECO_WANTRETURN)
2188       FIXME("ECO_WANTRETURN not implemented yet!\n");
2189
2190     return settings;
2191   }
2192   case EM_SETSEL:
2193   {
2194     ME_InvalidateSelection(editor);
2195     ME_SetSelection(editor, wParam, lParam);
2196     ME_InvalidateSelection(editor);
2197     HideCaret(editor->hWnd);
2198     ME_ShowCaret(editor);
2199     ME_SendSelChange(editor);
2200     return 0;
2201   }
2202   case EM_SETSCROLLPOS:
2203   {
2204     POINT *point = (POINT *)lParam;
2205     ME_ScrollAbs(editor, point->y);
2206     return 0;
2207   }
2208   case EM_AUTOURLDETECT:
2209   {
2210     if (wParam==1 || wParam ==0) 
2211     {
2212         editor->AutoURLDetect_bEnable = (BOOL)wParam;
2213         return 0;
2214     }
2215     return E_INVALIDARG;
2216   }
2217   case EM_GETAUTOURLDETECT:
2218   {
2219     return editor->AutoURLDetect_bEnable;
2220   }
2221   case EM_EXSETSEL:
2222   {
2223     int end;
2224     CHARRANGE range = *(CHARRANGE *)lParam;
2225
2226     TRACE("EM_EXSETSEL (%d,%d)\n", range.cpMin, range.cpMax);
2227
2228     ME_InvalidateSelection(editor);
2229     end = ME_SetSelection(editor, range.cpMin, range.cpMax);
2230     ME_InvalidateSelection(editor);
2231     HideCaret(editor->hWnd);
2232     ME_ShowCaret(editor);
2233     ME_SendSelChange(editor);
2234
2235     return end;
2236   }
2237   case EM_SHOWSCROLLBAR:
2238   {
2239     ShowScrollBar(editor->hWnd, wParam, lParam);
2240     return 0;
2241   }
2242   case EM_SETTEXTEX:
2243   {
2244     LPWSTR wszText;
2245     SETTEXTEX *pStruct = (SETTEXTEX *)wParam;
2246     size_t len;
2247     int from, to;
2248     ME_Style *style;
2249     int oldModify = editor->nModifyStep;
2250
2251     if (!pStruct) return 0;
2252
2253     TRACE("EM_SETTEXTEX - %s, flags %d, cp %d\n",
2254           pStruct->codepage == 1200 ? debugstr_w((LPCWSTR)lParam) : debugstr_a((LPCSTR)lParam),
2255           pStruct->flags, pStruct->codepage);
2256
2257     /* FIXME: make use of pStruct->codepage in the to unicode translation */
2258     wszText = lParam ? ME_ToUnicode(pStruct->codepage == 1200, (void *)lParam) : NULL;
2259     len = wszText ? lstrlenW(wszText) : 0;
2260
2261     if (pStruct->flags & ST_SELECTION) {
2262       ME_GetSelection(editor, &from, &to);
2263       style = ME_GetSelectionInsertStyle(editor);
2264       ME_InternalDeleteText(editor, from, to - from);
2265       if (pStruct->codepage != 1200 && lParam && !strncmp((char *)lParam, "{\\rtf", 5))
2266           ME_StreamInRTFString(editor, 0, (char *)lParam);
2267       else ME_InsertTextFromCursor(editor, 0, wszText, len, style);
2268       ME_ReleaseStyle(style);
2269
2270       if (editor->AutoURLDetect_bEnable) ME_UpdateSelectionLinkAttribute(editor);
2271     }
2272     else {
2273       ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor));
2274       if (pStruct->codepage != 1200 && lParam && !strncmp((char *)lParam, "{\\rtf", 5))
2275           ME_StreamInRTFString(editor, 0, (char *)lParam);
2276       else ME_InsertTextFromCursor(editor, 0, wszText, len, editor->pBuffer->pDefaultStyle);
2277       len = 1;
2278
2279       if (editor->AutoURLDetect_bEnable) ME_UpdateLinkAttribute(editor, 0, -1);
2280     }
2281     ME_CommitUndo(editor);
2282     if (!(pStruct->flags & ST_KEEPUNDO))
2283     {
2284       editor->nModifyStep = oldModify;
2285       ME_EmptyUndoStack(editor);
2286     }
2287     ME_UpdateRepaint(editor);
2288     return len;
2289   }
2290   case EM_SETBKGNDCOLOR:
2291   {
2292     LRESULT lColor;
2293     if (editor->rgbBackColor != -1) {
2294       DeleteObject(editor->hbrBackground);
2295       lColor = editor->rgbBackColor;
2296     }
2297     else lColor = GetSysColor(COLOR_WINDOW);
2298
2299     if (wParam)
2300     {
2301       editor->rgbBackColor = -1;
2302       editor->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
2303     }
2304     else
2305     {
2306       editor->rgbBackColor = lParam;
2307       editor->hbrBackground = CreateSolidBrush(editor->rgbBackColor);
2308     }
2309     if (editor->bRedraw)
2310     {
2311       InvalidateRect(hWnd, NULL, TRUE);
2312       UpdateWindow(hWnd);
2313     }
2314     return lColor;
2315   }
2316   case EM_GETMODIFY:
2317     return editor->nModifyStep == 0 ? 0 : -1;
2318   case EM_SETMODIFY:
2319   {
2320     if (wParam)
2321       editor->nModifyStep = 1;
2322     else
2323       editor->nModifyStep = 0;
2324     
2325     return 0;
2326   }
2327   case EM_SETREADONLY:
2328   {
2329     long nStyle = GetWindowLongW(hWnd, GWL_STYLE);
2330     if (wParam)
2331       nStyle |= ES_READONLY;
2332     else
2333       nStyle &= ~ES_READONLY;
2334     SetWindowLongW(hWnd, GWL_STYLE, nStyle);
2335     return 0;
2336   }
2337   case EM_SETEVENTMASK:
2338   {
2339     DWORD nOldMask = editor->nEventMask;
2340     
2341     editor->nEventMask = lParam;
2342     return nOldMask;
2343   }
2344   case EM_GETEVENTMASK:
2345     return editor->nEventMask;
2346   case EM_SETCHARFORMAT:
2347   {
2348     CHARFORMAT2W buf, *p;
2349     BOOL bRepaint = TRUE;
2350     p = ME_ToCF2W(&buf, (CHARFORMAT2W *)lParam);
2351     if (p == NULL) return 0;
2352     if (!wParam)
2353       ME_SetDefaultCharFormat(editor, p);
2354     else if (wParam == (SCF_WORD | SCF_SELECTION)) {
2355       FIXME("EM_SETCHARFORMAT: word selection not supported\n");
2356       return 0;
2357     } else if (wParam == SCF_ALL) {
2358       if (editor->mode & TM_PLAINTEXT)
2359         ME_SetDefaultCharFormat(editor, p);
2360       else {
2361         ME_SetCharFormat(editor, 0, ME_GetTextLength(editor), p);
2362         editor->nModifyStep = 1;
2363       }
2364     } else if (editor->mode & TM_PLAINTEXT) {
2365       return 0;
2366     } else {
2367       int from, to;
2368       ME_GetSelection(editor, &from, &to);
2369       bRepaint = (from != to);
2370       ME_SetSelectionCharFormat(editor, p);
2371       if (from != to) editor->nModifyStep = 1;
2372     }
2373     ME_CommitUndo(editor);
2374     if (bRepaint)
2375       ME_RewrapRepaint(editor);
2376     return 1;
2377   }
2378   case EM_GETCHARFORMAT:
2379   {
2380     CHARFORMAT2W tmp, *dst = (CHARFORMAT2W *)lParam;
2381     if (dst->cbSize != sizeof(CHARFORMATA) &&
2382         dst->cbSize != sizeof(CHARFORMATW) &&
2383         dst->cbSize != sizeof(CHARFORMAT2A) &&
2384         dst->cbSize != sizeof(CHARFORMAT2W))
2385       return 0;
2386     tmp.cbSize = sizeof(tmp);
2387     if (!wParam)
2388       ME_GetDefaultCharFormat(editor, &tmp);
2389     else
2390       ME_GetSelectionCharFormat(editor, &tmp);
2391     ME_CopyToCFAny(dst, &tmp);
2392     return tmp.dwMask;
2393   }
2394   case EM_SETPARAFORMAT:
2395     ME_SetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
2396     ME_RewrapRepaint(editor);
2397     ME_CommitUndo(editor);
2398     return 0;
2399   case EM_GETPARAFORMAT:
2400     ME_GetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
2401     return 0;
2402   case EM_GETFIRSTVISIBLELINE:
2403   {
2404     ME_DisplayItem *p = editor->pBuffer->pFirst;
2405     int y = ME_GetYScrollPos(editor);
2406     int ypara = 0;
2407     int count = 0;
2408     int ystart, yend;
2409     while(p) {
2410       p = ME_FindItemFwd(p, diStartRowOrParagraphOrEnd);
2411       if (p->type == diTextEnd)
2412         break;
2413       if (p->type == diParagraph) {
2414         ypara = p->member.para.nYPos;
2415         continue;
2416       }
2417       ystart = ypara + p->member.row.nYPos;
2418       yend = ystart + p->member.row.nHeight;
2419       if (y < yend) {
2420         break;
2421       }
2422       count++;
2423     }
2424     return count;
2425   }
2426   case EM_HIDESELECTION:
2427   {
2428      editor->bHideSelection = (wParam != 0);
2429      ME_InvalidateSelection(editor);
2430      return 0;
2431   }
2432   case EM_LINESCROLL:
2433   {
2434     ME_ScrollDown(editor, lParam * 8); /* FIXME follow the original */
2435     return TRUE; /* Should return false if a single line richedit control */
2436   }
2437   case WM_CLEAR:
2438   {
2439     int from, to;
2440     ME_GetSelection(editor, &from, &to);
2441     ME_InternalDeleteText(editor, from, to-from);
2442     ME_CommitUndo(editor);
2443     ME_UpdateRepaint(editor);
2444     return 0;
2445   }
2446   case EM_REPLACESEL:
2447   {
2448     int from, to;
2449     ME_Style *style;
2450     LPWSTR wszText = lParam ? ME_ToUnicode(unicode, (void *)lParam) : NULL;
2451     size_t len = wszText ? lstrlenW(wszText) : 0;
2452     TRACE("EM_REPLACESEL - %s\n", debugstr_w(wszText));
2453
2454     ME_GetSelection(editor, &from, &to);
2455     style = ME_GetSelectionInsertStyle(editor);
2456     ME_InternalDeleteText(editor, from, to-from);
2457     ME_InsertTextFromCursor(editor, 0, wszText, len, style);
2458     ME_ReleaseStyle(style);
2459     /* drop temporary style if line end */
2460     /*
2461      * FIXME question: does abc\n mean: put abc,
2462      * clear temp style, put \n? (would require a change)
2463      */
2464     if (len>0 && wszText[len-1] == '\n')
2465       ME_ClearTempStyle(editor);
2466     ME_EndToUnicode(unicode, wszText);
2467     ME_CommitUndo(editor);
2468     if (editor->AutoURLDetect_bEnable) ME_UpdateSelectionLinkAttribute(editor);
2469     if (!wParam)
2470       ME_EmptyUndoStack(editor);
2471     ME_UpdateRepaint(editor);
2472     return len;
2473   }
2474   case EM_SCROLLCARET:
2475   {
2476     int top, bottom; /* row's edges relative to document top */
2477     int nPos;
2478     ME_DisplayItem *para, *row;
2479     
2480     nPos = ME_GetYScrollPos(editor);
2481     row = ME_RowStart(editor->pCursors[0].pRun);
2482     para = ME_GetParagraph(row);
2483     top = para->member.para.nYPos + row->member.row.nYPos;
2484     bottom = top + row->member.row.nHeight;
2485     
2486     if (top < nPos) /* caret above window */
2487       ME_ScrollAbs(editor,  top);
2488     else if (nPos + editor->sizeWindow.cy < bottom) /*below*/
2489       ME_ScrollAbs(editor, bottom - editor->sizeWindow.cy);
2490     return 0;
2491   }
2492   case WM_SETFONT:
2493   {
2494     LOGFONTW lf;
2495     CHARFORMAT2W fmt;
2496     HDC hDC;
2497     BOOL bRepaint = LOWORD(lParam);
2498     
2499     if (!wParam)
2500       wParam = (WPARAM)GetStockObject(SYSTEM_FONT); 
2501     GetObjectW((HGDIOBJ)wParam, sizeof(LOGFONTW), &lf);
2502     hDC = GetDC(hWnd);
2503     ME_CharFormatFromLogFont(hDC, &lf, &fmt); 
2504     ReleaseDC(hWnd, hDC);   
2505     ME_SetCharFormat(editor, 0, ME_GetTextLength(editor), &fmt);
2506     ME_SetDefaultCharFormat(editor, &fmt);
2507
2508     ME_CommitUndo(editor);
2509     if (bRepaint)
2510       ME_RewrapRepaint(editor);
2511     return 0;
2512   }
2513   case WM_SETTEXT:
2514   {
2515     ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor));
2516     if (lParam)
2517     {
2518       TRACE("WM_SETTEXT lParam==%lx\n",lParam);
2519       if (!unicode && !strncmp((char *)lParam, "{\\rtf", 5))
2520       {
2521         /* Undocumented: WM_SETTEXT supports RTF text */
2522         ME_StreamInRTFString(editor, 0, (char *)lParam);
2523       }
2524       else
2525       {
2526         LPWSTR wszText = ME_ToUnicode(unicode, (void *)lParam);
2527         TRACE("WM_SETTEXT - %s\n", debugstr_w(wszText)); /* debugstr_w() */
2528         if (lstrlenW(wszText) > 0)
2529         {
2530           int len = -1;
2531
2532           /* uses default style! */
2533           if (!(GetWindowLongW(hWnd, GWL_STYLE) & ES_MULTILINE))
2534           {
2535             WCHAR * p;
2536
2537             p = wszText;
2538             while (*p != '\0' && *p != '\r' && *p != '\n') p++;
2539             len = p - wszText;
2540           }
2541           ME_InsertTextFromCursor(editor, 0, wszText, len, editor->pBuffer->pDefaultStyle);
2542         }
2543         ME_EndToUnicode(unicode, wszText);
2544       }
2545     }
2546     else
2547       TRACE("WM_SETTEXT - NULL\n");
2548     if (editor->AutoURLDetect_bEnable)
2549     {
2550       ME_UpdateLinkAttribute(editor, 0, -1);
2551     }
2552     ME_SetSelection(editor, 0, 0);
2553     editor->nModifyStep = 0;
2554     ME_CommitUndo(editor);
2555     ME_EmptyUndoStack(editor);
2556     ME_UpdateRepaint(editor);
2557     return 1;
2558   }
2559   case EM_CANPASTE:
2560   {
2561     UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
2562     if (IsClipboardFormatAvailable(nRTFFormat))
2563       return TRUE;
2564     if (IsClipboardFormatAvailable(CF_UNICODETEXT))
2565       return TRUE;
2566     return FALSE;
2567   }
2568   case WM_PASTE:
2569   {    
2570     DWORD dwFormat = 0;
2571     EDITSTREAM es;
2572     ME_GlobalDestStruct gds;
2573     UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
2574     UINT cf = 0;
2575
2576     if (IsClipboardFormatAvailable(nRTFFormat))
2577       cf = nRTFFormat, dwFormat = SF_RTF;
2578     else if (IsClipboardFormatAvailable(CF_UNICODETEXT))
2579       cf = CF_UNICODETEXT, dwFormat = SF_TEXT|SF_UNICODE;
2580     else
2581       return 0;
2582
2583     if (!OpenClipboard(hWnd))
2584       return 0;
2585     gds.hData = GetClipboardData(cf);
2586     gds.nLength = 0;
2587     es.dwCookie = (DWORD)&gds;
2588     es.pfnCallback = dwFormat == SF_RTF ? ME_ReadFromHGLOBALRTF : ME_ReadFromHGLOBALUnicode;
2589     ME_StreamIn(editor, dwFormat|SFF_SELECTION, &es, FALSE);
2590
2591     CloseClipboard();
2592     return 0;
2593   }
2594   case WM_CUT:
2595   case WM_COPY:
2596   {
2597     LPDATAOBJECT dataObj = NULL;
2598     CHARRANGE range;
2599     HRESULT hr = S_OK;
2600
2601     if (editor->cPasswordMask)
2602       return 0; /* Copying or Cutting masked text isn't allowed */
2603
2604     ME_GetSelection(editor, &range.cpMin, &range.cpMax);
2605     if(editor->lpOleCallback)
2606         hr = IRichEditOleCallback_GetClipboardData(editor->lpOleCallback, &range, RECO_COPY, &dataObj);
2607     if(FAILED(hr) || !dataObj)
2608         hr = ME_GetDataObject(editor, &range, &dataObj);
2609     if(SUCCEEDED(hr)) {
2610         hr = OleSetClipboard(dataObj);
2611         IDataObject_Release(dataObj);
2612     }
2613     if (SUCCEEDED(hr) && msg == WM_CUT)
2614     {
2615       ME_InternalDeleteText(editor, range.cpMin, range.cpMax-range.cpMin);
2616       ME_CommitUndo(editor);
2617       ME_UpdateRepaint(editor);
2618     }
2619     return 0;
2620   }
2621   case WM_GETTEXTLENGTH:
2622   {
2623     GETTEXTLENGTHEX how;
2624
2625     /* CR/LF conversion required in 2.0 mode, verbatim in 1.0 mode */
2626     how.flags = GTL_CLOSE | (editor->bEmulateVersion10 ? 0 : GTL_USECRLF) | GTL_NUMCHARS;
2627     how.codepage = unicode ? 1200 : CP_ACP;
2628     return ME_GetTextLengthEx(editor, &how);
2629   }
2630   case EM_GETTEXTLENGTHEX:
2631     return ME_GetTextLengthEx(editor, (GETTEXTLENGTHEX *)wParam);
2632   case WM_GETTEXT:
2633   {
2634     GETTEXTEX ex;
2635     LRESULT rc;
2636     LPSTR bufferA = NULL;
2637     LPWSTR bufferW = NULL;
2638
2639     if (unicode)
2640         bufferW = heap_alloc((wParam + 2) * sizeof(WCHAR));
2641     else
2642         bufferA = heap_alloc(wParam + 2);
2643
2644     ex.cb = (wParam + 2) * (unicode ? sizeof(WCHAR) : sizeof(CHAR));
2645     ex.flags = GT_USECRLF;
2646     ex.codepage = unicode ? 1200 : CP_ACP;
2647     ex.lpDefaultChar = NULL;
2648     ex.lpUsedDefChar = NULL;
2649     rc = RichEditWndProc_common(hWnd, EM_GETTEXTEX, (WPARAM)&ex, unicode ? (LPARAM)bufferW : (LPARAM)bufferA, unicode);
2650
2651     if (unicode)
2652     {
2653         memcpy((LPWSTR)lParam, bufferW, wParam * sizeof(WCHAR));
2654         if (lstrlenW(bufferW) >= wParam) rc = 0;
2655     }
2656     else
2657     {
2658         memcpy((LPSTR)lParam, bufferA, wParam);
2659         if (strlen(bufferA) >= wParam) rc = 0;
2660     }
2661     heap_free(bufferA);
2662     heap_free(bufferW);
2663     return rc;
2664   }
2665   case EM_GETTEXTEX:
2666   {
2667     GETTEXTEX *ex = (GETTEXTEX*)wParam;
2668     int nStart, nCount; /* in chars */
2669
2670     if (ex->flags & ~(GT_SELECTION | GT_USECRLF))
2671       FIXME("GETTEXTEX flags 0x%08x not supported\n", ex->flags & ~(GT_SELECTION | GT_USECRLF));
2672
2673     if (ex->flags & GT_SELECTION)
2674     {
2675       ME_GetSelection(editor, &nStart, &nCount);
2676       nCount -= nStart;
2677     }
2678     else
2679     {
2680       nStart = 0;
2681       nCount = 0x7fffffff;
2682     }
2683     if (ex->codepage == 1200)
2684     {
2685       nCount = min(nCount, ex->cb / sizeof(WCHAR) - 1);
2686       return ME_GetTextW(editor, (LPWSTR)lParam, nStart, nCount, ex->flags & GT_USECRLF);
2687     }
2688     else
2689     {
2690       /* potentially each char may be a CR, why calculate the exact value with O(N) when
2691         we can just take a bigger buffer? :)
2692         The above assumption still holds with CR/LF counters, since CR->CRLF expansion
2693         occurs only in richedit 2.0 mode, in which line breaks have only one CR
2694        */
2695       int crlfmul = (ex->flags & GT_USECRLF) ? 2 : 1;
2696       LPWSTR buffer;
2697       DWORD buflen = ex->cb;
2698       LRESULT rc;
2699       DWORD flags = 0;
2700
2701       nCount = min(nCount, ex->cb - 1);
2702       buffer = heap_alloc((crlfmul*nCount + 1) * sizeof(WCHAR));
2703
2704       buflen = ME_GetTextW(editor, buffer, nStart, nCount, ex->flags & GT_USECRLF);
2705       rc = WideCharToMultiByte(ex->codepage, flags, buffer, buflen+1, (LPSTR)lParam, ex->cb, ex->lpDefaultChar, ex->lpUsedDefChar);
2706       if (rc) rc--; /* do not count 0 terminator */
2707
2708       heap_free(buffer);
2709       return rc;
2710     }
2711   }
2712   case EM_GETSELTEXT:
2713   {
2714     int from, to;
2715     TEXTRANGEW tr; /* W and A differ only by rng->lpstrText */
2716     ME_GetSelection(editor, &from, &to);
2717     tr.chrg.cpMin = from;
2718     tr.chrg.cpMax = to;
2719     tr.lpstrText = (WCHAR *)lParam;
2720     return RichEditWndProc_common(hWnd, EM_GETTEXTRANGE, 0, (LPARAM)&tr, unicode);
2721   }
2722   case EM_GETSCROLLPOS:
2723   {
2724       POINT *point = (POINT *)lParam;
2725       point->x = 0; /* FIXME side scrolling not implemented */
2726       point->y = ME_GetYScrollPos(editor);
2727       return 1;
2728   }
2729   case EM_GETTEXTRANGE:
2730   {
2731     TEXTRANGEW *rng = (TEXTRANGEW *)lParam;
2732     TRACE("EM_GETTEXTRANGE min=%d max=%d unicode=%d emul1.0=%d length=%d\n",
2733       rng->chrg.cpMin, rng->chrg.cpMax, unicode,
2734       editor->bEmulateVersion10, ME_GetTextLength(editor));
2735     if (unicode)
2736       return ME_GetTextW(editor, rng->lpstrText, rng->chrg.cpMin, rng->chrg.cpMax-rng->chrg.cpMin, 0);
2737     else
2738     {
2739       int nLen = rng->chrg.cpMax-rng->chrg.cpMin;
2740       WCHAR *p = ALLOC_N_OBJ(WCHAR, nLen+1);
2741       int nChars = ME_GetTextW(editor, p, rng->chrg.cpMin, nLen, 0);
2742       /* FIXME this is a potential security hole (buffer overrun) 
2743          if you know more about wchar->mbyte conversion please explain
2744       */
2745       WideCharToMultiByte(CP_ACP, 0, p, nChars+1, (char *)rng->lpstrText, nLen+1, NULL, NULL);
2746       FREE_OBJ(p);
2747       return nChars;
2748     }
2749   }
2750   case EM_GETLINE:
2751   {
2752     ME_DisplayItem *run;
2753     const unsigned int nMaxChars = *(WORD *) lParam;
2754     unsigned int nCharsLeft = nMaxChars;
2755     char *dest = (char *) lParam;
2756     BOOL wroteNull = FALSE;
2757
2758     TRACE("EM_GETLINE: row=%d, nMaxChars=%d (%s)\n", (int) wParam, nMaxChars,
2759           unicode ? "Unicode" : "Ansi");
2760
2761     run = ME_FindRowWithNumber(editor, wParam);
2762     if (run == NULL)
2763       return 0;
2764
2765     while (nCharsLeft && (run = ME_FindItemFwd(run, diRunOrStartRow))
2766            && !(run->member.run.nFlags & MERF_ENDPARA))
2767     {
2768       unsigned int nCopy;
2769       ME_String *strText;
2770       if (run->type != diRun)
2771         break;
2772       strText = run->member.run.strText;
2773       nCopy = min(nCharsLeft, strText->nLen);
2774
2775       if (unicode)
2776         lstrcpynW((LPWSTR) dest, strText->szData, nCopy);
2777       else
2778         nCopy = WideCharToMultiByte(CP_ACP, 0, strText->szData, nCopy, dest,
2779                                     nCharsLeft, NULL, NULL);
2780       dest += nCopy * (unicode ? sizeof(WCHAR) : 1);
2781       nCharsLeft -= nCopy;
2782     }
2783
2784     /* append line termination, space allowing */
2785     if (nCharsLeft > 0)
2786     {
2787       if (run && (run->member.run.nFlags & MERF_ENDPARA))
2788       {
2789         unsigned int i;
2790         /* Write as many \r as encoded in end-of-paragraph, space allowing */
2791         for (i = 0; i < run->member.run.nCR && nCharsLeft > 0; i++, nCharsLeft--)
2792         {
2793           *((WCHAR *)dest) = '\r';
2794           dest += unicode ? sizeof(WCHAR) : 1;
2795         }
2796         /* Write as many \n as encoded in end-of-paragraph, space allowing */
2797         for (i = 0; i < run->member.run.nLF && nCharsLeft > 0; i++, nCharsLeft--)
2798         {
2799           *((WCHAR *)dest) = '\n';
2800           dest += unicode ? sizeof(WCHAR) : 1;
2801         }
2802       }
2803       if (nCharsLeft > 0)
2804       {
2805         if (unicode)
2806           *((WCHAR *)dest) = '\0';
2807         else
2808           *dest = '\0';
2809         nCharsLeft--;
2810         wroteNull = TRUE;
2811       }
2812     }
2813
2814     TRACE("EM_GETLINE: got %u characters\n", nMaxChars - nCharsLeft);
2815     return nMaxChars - nCharsLeft - (wroteNull ? 1 : 0);
2816   }
2817   case EM_GETLINECOUNT:
2818   {
2819     ME_DisplayItem *item = editor->pBuffer->pFirst->next;
2820     int nRows = 0;
2821
2822     ME_DisplayItem *prev_para = NULL, *last_para = NULL;
2823
2824     while (item != editor->pBuffer->pLast)
2825     {
2826       assert(item->type == diParagraph);
2827       prev_para = ME_FindItemBack(item, diRun);
2828       if (prev_para) {
2829         assert(prev_para->member.run.nFlags & MERF_ENDPARA);
2830       }
2831       nRows += item->member.para.nRows;
2832       item = item->member.para.next_para;
2833     }
2834     last_para = ME_FindItemBack(item, diRun);
2835     assert(last_para);
2836     assert(last_para->member.run.nFlags & MERF_ENDPARA);
2837     if (editor->bEmulateVersion10 && prev_para && last_para->member.run.nCharOfs == 0
2838         && prev_para->member.run.nCR == 1 && prev_para->member.run.nLF == 0)
2839     {
2840       /* In 1.0 emulation, the last solitary \r at the very end of the text
2841          (if one exists) is NOT a line break.
2842          FIXME: this is an ugly hack. This should have a more regular model. */
2843       nRows--;
2844     }
2845
2846     TRACE("EM_GETLINECOUNT: nRows==%d\n", nRows);
2847     return max(1, nRows);
2848   }
2849   case EM_LINEFROMCHAR:
2850   {
2851     if (wParam == -1)
2852       return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(editor, 1));
2853     else
2854       return ME_RowNumberFromCharOfs(editor, wParam);
2855   }
2856   case EM_EXLINEFROMCHAR:
2857   {
2858     if (lParam == -1)
2859       return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(editor,1));
2860     else    
2861       return ME_RowNumberFromCharOfs(editor, lParam);
2862   }
2863   case EM_LINEINDEX:
2864   {
2865     ME_DisplayItem *item, *para;
2866     int nCharOfs;
2867     
2868     if (wParam == -1)
2869       item = ME_FindItemBack(editor->pCursors[0].pRun, diStartRow);
2870     else
2871       item = ME_FindRowWithNumber(editor, wParam);
2872     if (!item)
2873       return -1;
2874     para = ME_GetParagraph(item);
2875     item = ME_FindItemFwd(item, diRun);
2876     nCharOfs = para->member.para.nCharOfs + item->member.run.nCharOfs;
2877     TRACE("EM_LINEINDEX: nCharOfs==%d\n", nCharOfs);
2878     return nCharOfs;
2879   }
2880   case EM_LINELENGTH:
2881   {
2882     ME_DisplayItem *item, *item_end;
2883     int nChars = 0, nThisLineOfs = 0, nNextLineOfs = 0;
2884     
2885     if (wParam > ME_GetTextLength(editor))
2886       return 0;
2887     if (wParam == -1)
2888     {
2889       FIXME("EM_LINELENGTH: returning number of unselected characters on lines with selection unsupported.\n");
2890       return 0;
2891     }
2892     item = ME_FindItemAtOffset(editor, diRun, wParam, NULL);
2893     item = ME_RowStart(item);
2894     nThisLineOfs = ME_CharOfsFromRunOfs(editor, ME_FindItemFwd(item, diRun), 0);
2895     item_end = ME_FindItemFwd(item, diStartRowOrParagraphOrEnd);
2896     if (item_end->type == diStartRow)
2897       nNextLineOfs = ME_CharOfsFromRunOfs(editor, ME_FindItemFwd(item_end, diRun), 0);
2898     else
2899     {
2900       ME_DisplayItem *endPara;
2901
2902       nNextLineOfs = ME_FindItemFwd(item, diParagraphOrEnd)->member.para.nCharOfs;
2903       endPara = ME_FindItemFwd(item, diParagraphOrEnd);
2904       endPara = ME_FindItemBack(endPara, diRun);
2905       assert(endPara);
2906       assert(endPara->type == diRun);
2907       assert(endPara->member.run.nFlags & MERF_ENDPARA);
2908       nNextLineOfs -= endPara->member.run.nCR + endPara->member.run.nLF;
2909     }
2910     nChars = nNextLineOfs - nThisLineOfs;
2911     TRACE("EM_LINELENGTH(%ld)==%d\n",wParam, nChars);
2912     return nChars;
2913   }
2914   case EM_EXLIMITTEXT:
2915   {
2916     if ((int)lParam < 0)
2917      return 0;
2918     if (lParam == 0)
2919       editor->nTextLimit = 65536;
2920     else
2921       editor->nTextLimit = (int) lParam;
2922     return 0;
2923   }
2924   case EM_LIMITTEXT:
2925   {
2926     if (wParam == 0)
2927       editor->nTextLimit = 65536;
2928     else
2929       editor->nTextLimit = (int) wParam;
2930     return 0;
2931   }
2932   case EM_GETLIMITTEXT:
2933   {
2934     return editor->nTextLimit;
2935   }
2936   case EM_FINDTEXT:
2937   {
2938     FINDTEXTA *ft = (FINDTEXTA *)lParam;
2939     int nChars = MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, NULL, 0);
2940     WCHAR *tmp;
2941     LRESULT r;
2942
2943     if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
2944       MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, tmp, nChars);
2945     r = ME_FindText(editor, wParam, &ft->chrg, tmp, NULL);
2946     FREE_OBJ( tmp );
2947     return r;
2948   }
2949   case EM_FINDTEXTEX:
2950   {
2951     FINDTEXTEXA *ex = (FINDTEXTEXA *)lParam;
2952     int nChars = MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, NULL, 0);
2953     WCHAR *tmp;
2954     LRESULT r;
2955
2956     if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
2957       MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, tmp, nChars);
2958     r = ME_FindText(editor, wParam, &ex->chrg, tmp, &ex->chrgText);
2959     FREE_OBJ( tmp );
2960     return r;
2961   }
2962   case EM_FINDTEXTW:
2963   {
2964     FINDTEXTW *ft = (FINDTEXTW *)lParam;
2965     return ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
2966   }
2967   case EM_FINDTEXTEXW:
2968   {
2969     FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
2970     return ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
2971   }
2972   case EM_GETZOOM:
2973     if (!wParam || !lParam)
2974       return FALSE;
2975     *(int *)wParam = editor->nZoomNumerator;
2976     *(int *)lParam = editor->nZoomDenominator;
2977     return TRUE;
2978   case EM_SETZOOM:
2979     return ME_SetZoom(editor, wParam, lParam);
2980   case EM_CHARFROMPOS:
2981     return ME_CharFromPos(editor, ((POINTL *)lParam)->x, ((POINTL *)lParam)->y);
2982   case EM_POSFROMCHAR:
2983   {
2984     ME_DisplayItem *pRun;
2985     int nCharOfs, nOffset, nLength;
2986     POINTL pt = {0,0};
2987     SCROLLINFO si;
2988     
2989     nCharOfs = wParam; 
2990     /* detect which API version we're dealing with */
2991     if (wParam >= 0x40000)
2992         nCharOfs = lParam;
2993     nLength = ME_GetTextLength(editor);
2994     
2995     if (nCharOfs < nLength) { 
2996         ME_RunOfsFromCharOfs(editor, nCharOfs, &pRun, &nOffset);
2997         assert(pRun->type == diRun);
2998         pt.y = pRun->member.run.pt.y;
2999         pt.x = pRun->member.run.pt.x + ME_PointFromChar(editor, &pRun->member.run, nOffset);
3000         pt.y += ME_GetParagraph(pRun)->member.para.nYPos;
3001     } else {
3002         pt.x = 0;
3003         pt.y = editor->pBuffer->pLast->member.para.nYPos;
3004     }
3005     pt.x += editor->selofs;
3006
3007     si.cbSize = sizeof(si);
3008     si.fMask = SIF_POS;
3009     if (GetScrollInfo(editor->hWnd, SB_VERT, &si)) pt.y -= si.nPos;
3010     si.cbSize = sizeof(si);
3011     si.fMask = SIF_POS;
3012     if (GetScrollInfo(editor->hWnd, SB_HORZ, &si)) pt.x -= si.nPos;
3013
3014     if (wParam >= 0x40000) {
3015         *(POINTL *)wParam = pt;
3016     }
3017     return (wParam >= 0x40000) ? 0 : MAKELONG( pt.x, pt.y );
3018   }
3019   case WM_CREATE:
3020     GetClientRect(hWnd, &editor->rcFormat);
3021     if (GetWindowLongW(hWnd, GWL_STYLE) & WS_HSCROLL)
3022     { /* Squelch the default horizontal scrollbar it would make */
3023       ShowScrollBar(editor->hWnd, SB_HORZ, FALSE);
3024     }
3025     ME_CommitUndo(editor);
3026     ME_WrapMarkedParagraphs(editor);
3027     ME_MoveCaret(editor);
3028     return 0;
3029   case WM_DESTROY:
3030     ME_DestroyEditor(editor);
3031     SetWindowLongPtrW(hWnd, 0, 0);
3032     return 0;
3033   case WM_LBUTTONDBLCLK:
3034   case WM_LBUTTONDOWN:
3035   {
3036     ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3037     if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3038         !ME_FilterEvent(editor, msg, &wParam, &lParam))
3039       return 0;
3040     SetFocus(hWnd);
3041     ME_LButtonDown(editor, (short)LOWORD(lParam), (short)HIWORD(lParam),
3042                    ME_CalculateClickCount(hWnd, msg, wParam, lParam));
3043     SetCapture(hWnd);
3044     ME_LinkNotify(editor,msg,wParam,lParam);
3045     if (!ME_SetCursor(editor, LOWORD(lParam))) goto do_default;
3046     break;
3047   }
3048   case WM_MOUSEMOVE:
3049     if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3050         !ME_FilterEvent(editor, msg, &wParam, &lParam))
3051       return 0;
3052     if (GetCapture() == hWnd)
3053       ME_MouseMove(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
3054     ME_LinkNotify(editor,msg,wParam,lParam);
3055     if (!ME_SetCursor(editor, LOWORD(lParam))) goto do_default;
3056     break;
3057   case WM_LBUTTONUP:
3058     if (GetCapture() == hWnd)
3059       ReleaseCapture();
3060     if (editor->nSelectionType == stDocument)
3061       editor->nSelectionType = stPosition;
3062     if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3063         !ME_FilterEvent(editor, msg, &wParam, &lParam))
3064       return 0;
3065     else
3066     {
3067       BOOL ret;
3068       ret = ME_SetCursor(editor, LOWORD(lParam));
3069       ME_LinkNotify(editor,msg,wParam,lParam);
3070       if (!ret) goto do_default;
3071     }
3072     break;
3073   case WM_RBUTTONUP:
3074   case WM_RBUTTONDOWN:
3075     ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3076     if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3077         !ME_FilterEvent(editor, msg, &wParam, &lParam))
3078       return 0;
3079     goto do_default;
3080   case WM_CONTEXTMENU:
3081     if (!ME_ShowContextMenu(editor, (short)LOWORD(lParam), (short)HIWORD(lParam)))
3082       goto do_default;
3083     break;
3084   case WM_PAINT:
3085     if (editor->bRedraw)
3086     {
3087       HDC hDC;
3088       PAINTSTRUCT ps;
3089
3090       hDC = BeginPaint(hWnd, &ps);
3091       ME_PaintContent(editor, hDC, FALSE, &ps.rcPaint);
3092       EndPaint(hWnd, &ps);
3093     }
3094     break;
3095   case WM_SETFOCUS:
3096     editor->bHaveFocus = TRUE;
3097     ME_ShowCaret(editor);
3098     ME_SendOldNotify(editor, EN_SETFOCUS);
3099     return 0;
3100   case WM_KILLFOCUS:
3101     ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3102     editor->bHaveFocus = FALSE;
3103     ME_HideCaret(editor);
3104     ME_SendOldNotify(editor, EN_KILLFOCUS);
3105     return 0;
3106   case WM_ERASEBKGND:
3107   {
3108     if (editor->bRedraw)
3109     {
3110       HDC hDC = (HDC)wParam;
3111       RECT rc;
3112       if (GetUpdateRect(hWnd,&rc,TRUE))
3113       {
3114         FillRect(hDC, &rc, editor->hbrBackground);
3115       }
3116     }
3117     return 1;
3118   }
3119   case WM_COMMAND:
3120     TRACE("editor wnd command = %d\n", LOWORD(wParam));
3121     return 0;
3122   case WM_KEYUP:
3123     if ((editor->nEventMask & ENM_KEYEVENTS) &&
3124         !ME_FilterEvent(editor, msg, &wParam, &lParam))
3125       return 0;
3126     goto do_default;
3127   case WM_KEYDOWN:
3128     if ((editor->nEventMask & ENM_KEYEVENTS) &&
3129         !ME_FilterEvent(editor, msg, &wParam, &lParam))
3130       return 0;
3131     if (ME_KeyDown(editor, LOWORD(wParam)))
3132       return 0;
3133     goto do_default;
3134   case WM_CHAR: 
3135   {
3136     WCHAR wstr;
3137
3138     if (unicode)
3139         wstr = (WCHAR)wParam;
3140     else
3141     {
3142         CHAR charA = wParam;
3143         MultiByteToWideChar(CP_ACP, 0, &charA, 1, &wstr, 1);
3144     }
3145
3146     switch (wstr)
3147     {
3148     case 1: /* Ctrl-A */
3149       ME_SetSelection(editor, 0, -1);
3150       return 0;
3151     case 3: /* Ctrl-C */
3152       SendMessageW(editor->hWnd, WM_COPY, 0, 0);
3153       return 0;
3154     }
3155     
3156     if (GetWindowLongW(editor->hWnd, GWL_STYLE) & ES_READONLY) {
3157       MessageBeep(MB_ICONERROR);
3158       return 0; /* FIXME really 0 ? */
3159     }
3160
3161     switch (wstr)
3162     {
3163     case 22: /* Ctrl-V */
3164       SendMessageW(editor->hWnd, WM_PASTE, 0, 0);
3165       return 0;
3166     case 24: /* Ctrl-X */
3167       SendMessageW(editor->hWnd, WM_CUT, 0, 0);
3168       return 0;
3169     case 25: /* Ctrl-Y */
3170       SendMessageW(editor->hWnd, EM_REDO, 0, 0);
3171       return 0;
3172     case 26: /* Ctrl-Z */
3173       SendMessageW(editor->hWnd, EM_UNDO, 0, 0);
3174       return 0;
3175     }
3176     if (((unsigned)wstr)>=' '
3177         || (wstr=='\r' && (GetWindowLongW(hWnd, GWL_STYLE) & ES_MULTILINE))
3178         || wstr=='\t') {
3179       /* FIXME maybe it would make sense to call EM_REPLACESEL instead ? */
3180       /* WM_CHAR is restricted to nTextLimit */
3181       int from, to;
3182       ME_GetSelection(editor, &from, &to);
3183       if(editor->nTextLimit > ME_GetTextLength(editor) - (to-from))
3184       {
3185         ME_Style *style = ME_GetInsertStyle(editor, 0);
3186         ME_SaveTempStyle(editor);
3187         ME_ContinueCoalescingTransaction(editor);
3188         if (wstr == '\r' && (GetKeyState(VK_SHIFT) & 0x8000))
3189           ME_InsertEndRowFromCursor(editor, 0);
3190         else
3191           ME_InsertTextFromCursor(editor, 0, &wstr, 1, style);
3192         ME_ReleaseStyle(style);
3193         ME_CommitCoalescingUndo(editor);
3194       }
3195
3196       if (editor->AutoURLDetect_bEnable) ME_UpdateSelectionLinkAttribute(editor);
3197
3198       ME_UpdateRepaint(editor);
3199     }
3200     return 0;
3201   }
3202   case EM_STOPGROUPTYPING:
3203     ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3204     return 0;
3205   case EM_SCROLL: /* fall through */
3206   case WM_VSCROLL: 
3207   {
3208     int origNPos;
3209     int lineHeight;
3210     
3211     origNPos = ME_GetYScrollPos(editor);
3212     lineHeight = 24;
3213     
3214     if (editor && editor->pBuffer && editor->pBuffer->pDefaultStyle)
3215       lineHeight = editor->pBuffer->pDefaultStyle->tm.tmHeight;
3216     if (lineHeight <= 0) lineHeight = 24;
3217     
3218     switch(LOWORD(wParam)) 
3219     {
3220       case SB_LINEUP:
3221         ME_ScrollUp(editor,lineHeight);
3222         break;
3223       case SB_LINEDOWN:
3224         ME_ScrollDown(editor,lineHeight);
3225         break;
3226       case SB_PAGEUP:
3227         ME_ScrollUp(editor,editor->sizeWindow.cy);
3228         break;
3229       case SB_PAGEDOWN:
3230         ME_ScrollDown(editor,editor->sizeWindow.cy);
3231         break;
3232       case SB_THUMBTRACK:
3233       case SB_THUMBPOSITION:
3234         ME_ScrollAbs(editor,HIWORD(wParam));
3235         break;
3236     }
3237     if (msg == EM_SCROLL)
3238       return 0x00010000 | (((ME_GetYScrollPos(editor) - origNPos)/lineHeight) & 0xffff);
3239     break;
3240   }
3241   case WM_MOUSEWHEEL:
3242   {
3243     int gcWheelDelta;
3244     UINT pulScrollLines;
3245
3246     if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3247         !ME_FilterEvent(editor, msg, &wParam, &lParam))
3248       return 0;
3249
3250     SystemParametersInfoW(SPI_GETWHEELSCROLLLINES,0, &pulScrollLines, 0);
3251     gcWheelDelta = -GET_WHEEL_DELTA_WPARAM(wParam);
3252     
3253     if (abs(gcWheelDelta) >= WHEEL_DELTA && pulScrollLines)
3254     {
3255       /* FIXME follow the original */
3256       ME_ScrollDown(editor,pulScrollLines * (gcWheelDelta / WHEEL_DELTA) * 8); 
3257     }
3258     break;
3259   }
3260   case EM_GETRECT:
3261   {
3262     *((RECT *)lParam) = editor->rcFormat;
3263     return 0;
3264   }
3265   case EM_SETRECT:
3266   case EM_SETRECTNP:
3267   {
3268     if (lParam)
3269     {
3270       RECT *rc = (RECT *)lParam;
3271       
3272       if (wParam)
3273       {
3274         editor->rcFormat.left += rc->left;
3275         editor->rcFormat.top += rc->top;
3276         editor->rcFormat.right += rc->right;
3277         editor->rcFormat.bottom += rc->bottom;
3278       }
3279       else
3280       {
3281         editor->rcFormat = *rc;
3282       }
3283     }
3284     else
3285     {
3286       GetClientRect(hWnd, &editor->rcFormat);
3287     }
3288     if (msg != EM_SETRECTNP)
3289       ME_RewrapRepaint(editor);
3290     return 0;
3291   }
3292   case EM_REQUESTRESIZE:
3293     ME_SendRequestResize(editor, TRUE);
3294     return 0;
3295   case WM_SETREDRAW:
3296     if ((editor->bRedraw = wParam))
3297       ME_RewrapRepaint(editor);
3298     return 0;
3299   case WM_SIZE:
3300   {
3301     GetClientRect(hWnd, &editor->rcFormat);
3302     ME_RewrapRepaint(editor);
3303     return DefWindowProcW(hWnd, msg, wParam, lParam);
3304   }
3305   /* IME messages to make richedit controls IME aware */
3306   case WM_IME_SETCONTEXT:
3307   case WM_IME_CONTROL:
3308   case WM_IME_SELECT:
3309   case WM_IME_COMPOSITIONFULL:
3310     return 0;
3311   case WM_IME_STARTCOMPOSITION:
3312   {
3313     editor->imeStartIndex=ME_GetCursorOfs(editor,0);
3314     ME_DeleteSelection(editor);
3315     ME_CommitUndo(editor);
3316     ME_UpdateRepaint(editor);
3317     return 0;
3318   }
3319   case WM_IME_COMPOSITION:
3320   {
3321     HIMC hIMC;
3322
3323     ME_Style *style = ME_GetInsertStyle(editor, 0);
3324     hIMC = ImmGetContext(hWnd);
3325     ME_DeleteSelection(editor);
3326     ME_CommitUndo(editor);
3327     ME_SaveTempStyle(editor);
3328     if (lParam & GCS_RESULTSTR)
3329     {
3330         LPWSTR lpCompStr = NULL;
3331         DWORD dwBufLen;
3332
3333         dwBufLen = ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, NULL, 0);
3334         lpCompStr = HeapAlloc(GetProcessHeap(),0,dwBufLen + sizeof(WCHAR));
3335         ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, lpCompStr, dwBufLen);
3336         lpCompStr[dwBufLen/sizeof(WCHAR)] = 0;
3337         ME_InsertTextFromCursor(editor,0,lpCompStr,dwBufLen/sizeof(WCHAR),style);
3338     }
3339     else if (lParam & GCS_COMPSTR)
3340     {
3341         LPWSTR lpCompStr = NULL;
3342         DWORD dwBufLen;
3343
3344         dwBufLen = ImmGetCompositionStringW(hIMC, GCS_COMPSTR, NULL, 0);
3345         lpCompStr = HeapAlloc(GetProcessHeap(),0,dwBufLen + sizeof(WCHAR));
3346         ImmGetCompositionStringW(hIMC, GCS_COMPSTR, lpCompStr, dwBufLen);
3347         lpCompStr[dwBufLen/sizeof(WCHAR)] = 0;
3348
3349         ME_InsertTextFromCursor(editor,0,lpCompStr,dwBufLen/sizeof(WCHAR),style);
3350         ME_SetSelection(editor,editor->imeStartIndex,
3351                         editor->imeStartIndex + dwBufLen/sizeof(WCHAR));
3352     }
3353     ME_ReleaseStyle(style);
3354     ME_UpdateRepaint(editor);
3355     return 0;
3356   }
3357   case WM_IME_ENDCOMPOSITION:
3358   {
3359     ME_DeleteSelection(editor);
3360     editor->imeStartIndex=-1;
3361     return 0;
3362   }
3363   case EM_GETOLEINTERFACE:
3364   {
3365     LPVOID *ppvObj = (LPVOID*) lParam;
3366     return CreateIRichEditOle(editor, ppvObj);
3367   }
3368   case EM_GETPASSWORDCHAR:
3369   {
3370     return editor->cPasswordMask;
3371   }
3372   case EM_SETOLECALLBACK:
3373     if(editor->lpOleCallback)
3374       IUnknown_Release(editor->lpOleCallback);
3375     editor->lpOleCallback = (LPRICHEDITOLECALLBACK)lParam;
3376     if(editor->lpOleCallback)
3377       IUnknown_AddRef(editor->lpOleCallback);
3378     return TRUE;
3379   case EM_GETWORDBREAKPROC:
3380     return (LRESULT)editor->pfnWordBreak;
3381   case EM_SETWORDBREAKPROC:
3382   {
3383     EDITWORDBREAKPROCW pfnOld = editor->pfnWordBreak;
3384
3385     editor->pfnWordBreak = (EDITWORDBREAKPROCW)lParam;
3386     return (LRESULT)pfnOld;
3387   }
3388   case EM_SETTEXTMODE:
3389   {
3390     LRESULT ret;
3391     int mask = 0;
3392     int changes = 0;
3393     ret = RichEditWndProc_common(hWnd, WM_GETTEXTLENGTH, 0, 0, unicode);
3394     if (!ret)
3395     {
3396       /*Check for valid wParam*/
3397       if ((((wParam & TM_RICHTEXT) && ((wParam & TM_PLAINTEXT) << 1))) ||
3398           (((wParam & TM_MULTILEVELUNDO) && ((wParam & TM_SINGLELEVELUNDO) << 1))) ||
3399           (((wParam & TM_MULTICODEPAGE) && ((wParam & TM_SINGLECODEPAGE) << 1))))
3400         return 1;
3401       else
3402       {
3403         if (wParam & (TM_RICHTEXT | TM_PLAINTEXT))
3404         {
3405           mask |= (TM_RICHTEXT | TM_PLAINTEXT);
3406           changes |= (wParam & (TM_RICHTEXT | TM_PLAINTEXT));
3407         }
3408         /*FIXME: Currently no support for undo level and code page options*/ 
3409         editor->mode = (editor->mode & (~mask)) | changes;
3410         return 0;
3411       }
3412     }
3413     return ret;
3414   }
3415   case EM_SETPASSWORDCHAR:
3416   {
3417     editor->cPasswordMask = wParam;
3418     ME_RewrapRepaint(editor);
3419     return 0;
3420   }
3421   case EM_SETTARGETDEVICE:
3422     if (wParam == 0)
3423     {
3424       BOOL new = (lParam == 0);
3425       if (editor->bWordWrap != new)
3426       {
3427         editor->bWordWrap = new;
3428         ME_RewrapRepaint(editor);
3429       }
3430     }
3431     else FIXME("Unsupported yet non NULL device in EM_SETTARGETDEVICE\n");
3432     break;
3433   default:
3434   do_default:
3435     return DefWindowProcW(hWnd, msg, wParam, lParam);
3436   }
3437   return 0L;
3438 }
3439
3440 static LRESULT WINAPI RichEditWndProcW(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
3441 {
3442     BOOL unicode = TRUE;
3443
3444     /* Under Win9x RichEdit20W returns ANSI strings, see the tests. */
3445     if (msg == WM_GETTEXT && (GetVersion() & 0x80000000))
3446         unicode = FALSE;
3447
3448     return RichEditWndProc_common(hWnd, msg, wParam, lParam, unicode);
3449 }
3450
3451 static LRESULT WINAPI RichEditWndProcA(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
3452 {
3453     return RichEditWndProc_common(hWnd, msg, wParam, lParam, FALSE);
3454 }
3455
3456 /******************************************************************
3457  *        RichEditANSIWndProc (RICHED20.10)
3458  */
3459 LRESULT WINAPI RichEditANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
3460 {
3461     return RichEditWndProcA(hWnd, msg, wParam, lParam);
3462 }
3463
3464 /******************************************************************
3465  *        RichEdit10ANSIWndProc (RICHED20.9)
3466  */
3467 LRESULT WINAPI RichEdit10ANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
3468 {
3469   LRESULT result;
3470   
3471   /* FIXME: this is NOT the same as 2.0 version */
3472   result = RichEditANSIWndProc(hWnd, msg, wParam, lParam);
3473   if (msg == WM_NCCREATE)
3474   {
3475     ME_TextEditor *editor = (ME_TextEditor *)GetWindowLongPtrW(hWnd, 0);
3476     
3477     editor->bEmulateVersion10 = TRUE;
3478     editor->pBuffer->pLast->member.para.nCharOfs = 2;
3479     assert(editor->pBuffer->pLast->prev->type == diRun);
3480     assert(editor->pBuffer->pLast->prev->member.run.nFlags & MERF_ENDPARA);
3481     editor->pBuffer->pLast->prev->member.run.nLF = 1;
3482   }
3483   return result;
3484 }
3485
3486 void ME_SendOldNotify(ME_TextEditor *editor, int nCode)
3487 {
3488   HWND hWnd = editor->hWnd;
3489   SendMessageA(GetParent(hWnd), WM_COMMAND, (nCode<<16)|GetWindowLongW(hWnd, GWLP_ID), (LPARAM)hWnd);
3490 }
3491
3492 void ME_LinkNotify(ME_TextEditor *editor, UINT msg, WPARAM wParam, LPARAM lParam)
3493 {
3494   int x,y;
3495   ME_Cursor tmpCursor;
3496   int nCharOfs; /* The start of the clicked text. Absolute character offset */
3497
3498   ME_Run *tmpRun;
3499
3500   ENLINK info;
3501   x = (short)LOWORD(lParam);
3502   y = (short)HIWORD(lParam);
3503   nCharOfs = ME_CharFromPos(editor, x, y);
3504   if (nCharOfs < 0) return;
3505
3506   ME_CursorFromCharOfs(editor, nCharOfs, &tmpCursor);
3507   tmpRun = &tmpCursor.pRun->member.run;
3508
3509   if ((tmpRun->style->fmt.dwMask & CFM_LINK)
3510     && (tmpRun->style->fmt.dwEffects & CFE_LINK))
3511   { /* The clicked run has CFE_LINK set */
3512     info.nmhdr.hwndFrom = editor->hWnd;
3513     info.nmhdr.idFrom = GetWindowLongW(editor->hWnd, GWLP_ID);
3514     info.nmhdr.code = EN_LINK;
3515     info.msg = msg;
3516     info.wParam = wParam;
3517     info.lParam = lParam;
3518     info.chrg.cpMin = ME_CharOfsFromRunOfs(editor,tmpCursor.pRun,0);
3519     info.chrg.cpMax = info.chrg.cpMin + ME_StrVLen(tmpRun->strText);
3520     SendMessageW(GetParent(editor->hWnd), WM_NOTIFY,info.nmhdr.idFrom, (LPARAM)&info);
3521   }  
3522 }
3523
3524 int ME_CountParagraphsBetween(ME_TextEditor *editor, int from, int to)
3525 {
3526   ME_DisplayItem *item = ME_FindItemFwd(editor->pBuffer->pFirst, diParagraph);
3527   int i = 0;
3528   
3529   while(item && item->member.para.next_para->member.para.nCharOfs <= from)
3530     item = item->member.para.next_para;
3531   if (!item)
3532     return 0;
3533   while(item && item->member.para.next_para->member.para.nCharOfs <= to) {
3534     item = item->member.para.next_para;
3535     i++;
3536   }
3537   return i;
3538 }
3539
3540
3541 int ME_GetTextW(ME_TextEditor *editor, WCHAR *buffer, int nStart, int nChars, int bCRLF)
3542 {
3543   ME_DisplayItem *item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
3544   int nWritten = 0;
3545   WCHAR *pStart = buffer;
3546   
3547   if (!item) {
3548     *buffer = 0;
3549     return 0;
3550   }
3551   
3552   /* bCRLF flag is only honored in 2.0 and up. 1.0 must always return text verbatim */
3553   if (editor->bEmulateVersion10) bCRLF = 0;
3554
3555   if (nStart)
3556   {
3557     int nLen = ME_StrLen(item->member.run.strText) - nStart;
3558     if (nLen > nChars)
3559       nLen = nChars;
3560     CopyMemory(buffer, item->member.run.strText->szData + nStart, sizeof(WCHAR)*nLen);
3561     nChars -= nLen;
3562     nWritten += nLen;
3563     buffer += nLen;
3564     if (!nChars) {
3565       *buffer = 0;
3566       return nWritten;
3567     }
3568     nStart = 0;
3569     item = ME_FindItemFwd(item, diRun);
3570   }
3571   
3572   while(nChars && item)
3573   {
3574     int nLen = ME_StrLen(item->member.run.strText);
3575     if (item->member.run.nFlags & MERF_ENDPARA)
3576        nLen = item->member.run.nCR + item->member.run.nLF;
3577     if (nLen > nChars)
3578       nLen = nChars;
3579
3580     if (item->member.run.nFlags & MERF_ENDPARA)
3581     {
3582       if (!ME_FindItemFwd(item, diRun))
3583         /* No '\r' is appended to the last paragraph. */
3584         nLen = 0;
3585       else if (bCRLF && nChars == 1) {
3586         nLen = 0;
3587         nChars = 0;
3588       } else {
3589         if (bCRLF)
3590         {
3591           /* richedit 2.0 case - actual line-break is \r but should report \r\n */
3592           assert(nLen == 1);
3593           *buffer++ = '\r';
3594           *buffer = '\n'; /* Later updated by nLen==1 at the end of the loop */
3595           nWritten++;
3596         }
3597         else
3598         {
3599           int i, j;
3600
3601           /* richedit 2.0 verbatim has only \r. richedit 1.0 should honor encodings */
3602           i = 0;
3603           while (nChars - i > 0 && i < item->member.run.nCR)
3604           {
3605             buffer[i] = '\r'; i++;
3606           }
3607           j = 0;
3608           while (nChars - i - j > 0 && j < item->member.run.nLF)
3609           {
3610             buffer[i+j] = '\n'; j++;
3611           }
3612         }
3613       }
3614     }
3615     else
3616       CopyMemory(buffer, item->member.run.strText->szData, sizeof(WCHAR)*nLen);
3617     nChars -= nLen;
3618     nWritten += nLen;
3619     buffer += nLen;    
3620       
3621     if (!nChars)
3622     {
3623       TRACE("nWritten=%d, actual=%d\n", nWritten, buffer-pStart);
3624       *buffer = 0;
3625       return nWritten;
3626     }
3627     item = ME_FindItemFwd(item, diRun);
3628   }
3629   *buffer = 0;
3630   TRACE("nWritten=%d, actual=%d\n", nWritten, buffer-pStart);
3631   return nWritten;  
3632 }
3633
3634 static BOOL ME_RegisterEditorClass(HINSTANCE hInstance)
3635 {
3636   WNDCLASSW wcW;
3637   WNDCLASSA wcA;
3638   
3639   wcW.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
3640   wcW.lpfnWndProc = RichEditWndProcW;
3641   wcW.cbClsExtra = 0;
3642   wcW.cbWndExtra = sizeof(ME_TextEditor *);
3643   wcW.hInstance = NULL; /* hInstance would register DLL-local class */
3644   wcW.hIcon = NULL;
3645   wcW.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
3646   wcW.hbrBackground = (HBRUSH)GetStockObject(NULL_BRUSH);
3647   wcW.lpszMenuName = NULL;
3648
3649   if (is_version_nt())
3650   {
3651     wcW.lpszClassName = RichEdit20W;
3652     if (!RegisterClassW(&wcW)) return FALSE;
3653     wcW.lpszClassName = RichEdit50W;
3654     if (!RegisterClassW(&wcW)) return FALSE;
3655   }
3656   else
3657   {
3658     /* WNDCLASSA/W have the same layout */
3659     wcW.lpszClassName = (LPCWSTR)"RichEdit20W";
3660     if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
3661     wcW.lpszClassName = (LPCWSTR)"RichEdit50W";
3662     if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
3663   }
3664
3665   wcA.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
3666   wcA.lpfnWndProc = RichEditWndProcA;
3667   wcA.cbClsExtra = 0;
3668   wcA.cbWndExtra = sizeof(ME_TextEditor *);
3669   wcA.hInstance = NULL; /* hInstance would register DLL-local class */
3670   wcA.hIcon = NULL;
3671   wcA.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
3672   wcA.hbrBackground = (HBRUSH)GetStockObject(NULL_BRUSH);
3673   wcA.lpszMenuName = NULL;
3674   wcA.lpszClassName = "RichEdit20A";
3675   if (!RegisterClassA(&wcA)) return FALSE;
3676   wcA.lpszClassName = "RichEdit50A";
3677   if (!RegisterClassA(&wcA)) return FALSE;
3678
3679   return TRUE;
3680 }
3681
3682 LRESULT WINAPI REComboWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
3683   /* FIXME: Not implemented */
3684   TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
3685         hWnd, msg, get_msg_name(msg), wParam, lParam);
3686   return DefWindowProcW(hWnd, msg, wParam, lParam);
3687 }
3688
3689 LRESULT WINAPI REListWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
3690   /* FIXME: Not implemented */
3691   TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
3692         hWnd, msg, get_msg_name(msg), wParam, lParam);
3693   return DefWindowProcW(hWnd, msg, wParam, lParam);
3694 }
3695
3696 /******************************************************************
3697  *        REExtendedRegisterClass (RICHED20.8)
3698  *
3699  * FIXME undocumented
3700  * Need to check for errors and implement controls and callbacks 
3701  */
3702 LRESULT WINAPI REExtendedRegisterClass(void)
3703 {
3704   WNDCLASSW wcW;
3705   UINT result;
3706
3707   FIXME("semi stub\n");
3708
3709   wcW.cbClsExtra = 0;
3710   wcW.cbWndExtra = 4;
3711   wcW.hInstance = NULL;
3712   wcW.hIcon = NULL;
3713   wcW.hCursor = NULL;
3714   wcW.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
3715   wcW.lpszMenuName = NULL;
3716
3717   if (!ME_ListBoxRegistered)
3718   {
3719       wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS;
3720       wcW.lpfnWndProc = REListWndProc;
3721       wcW.lpszClassName = REListBox20W;
3722       if (RegisterClassW(&wcW)) ME_ListBoxRegistered = TRUE;
3723   }
3724
3725   if (!ME_ComboBoxRegistered)
3726   {
3727       wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS | CS_VREDRAW | CS_HREDRAW;
3728       wcW.lpfnWndProc = REComboWndProc;
3729       wcW.lpszClassName = REComboBox20W;
3730       if (RegisterClassW(&wcW)) ME_ComboBoxRegistered = TRUE;  
3731   }
3732
3733   result = 0;
3734   if (ME_ListBoxRegistered)
3735       result += 1;
3736   if (ME_ComboBoxRegistered)
3737       result += 2;
3738
3739   return result;
3740 }
3741
3742 int ME_AutoURLDetect(ME_TextEditor *editor, WCHAR curChar) 
3743 {
3744   struct prefix_s {
3745     const char *text;
3746     int length;
3747   } prefixes[12] = {
3748     {"http:", 5},
3749     {"file:", 6},
3750     {"mailto:", 8},
3751     {"ftp:", 5},
3752     {"https:", 7},
3753     {"gopher:", 8},
3754     {"nntp:", 6},
3755     {"prospero:", 10},
3756     {"telnet:", 8},
3757     {"news:", 6},
3758     {"wais:", 6},
3759     {"www.", 5}
3760   };
3761   CHARRANGE ins_pt;
3762   int curf_ef, link_ef, def_ef;
3763   int cur_prefx, prefx_cnt;
3764   int sel_min, sel_max;
3765   int car_pos = 0;
3766   int text_pos=-1;
3767   int URLmin, URLmax = 0;
3768   FINDTEXTA ft;
3769   CHARFORMAT2W cur_format;
3770   CHARFORMAT2W default_format;
3771   CHARFORMAT2W link;
3772   RichEditANSIWndProc(editor->hWnd, EM_EXGETSEL, (WPARAM) 0, (LPARAM) &ins_pt);
3773   sel_min = ins_pt.cpMin;
3774   sel_max = ins_pt.cpMax;
3775   if (sel_min==sel_max) 
3776     car_pos = sel_min;
3777   if (sel_min!=sel_max)
3778     car_pos = ME_GetTextLength(editor)+1;   
3779   cur_format.cbSize = sizeof(cur_format);
3780   default_format.cbSize = sizeof(default_format);
3781   RichEditANSIWndProc(editor->hWnd, EM_GETCHARFORMAT, SCF_SELECTION, (LPARAM) &cur_format);
3782   RichEditANSIWndProc(editor->hWnd, EM_GETCHARFORMAT, SCF_DEFAULT, (LPARAM) &default_format);
3783   link.cbSize = sizeof(link);
3784   link.dwMask = CFM_LINK;
3785   link.dwEffects = CFE_LINK;
3786   curf_ef = cur_format.dwEffects & link.dwEffects;
3787   def_ef = default_format.dwEffects & link.dwEffects;
3788   link_ef = link.dwEffects & link.dwEffects;
3789   if (curf_ef == link_ef) 
3790   {
3791     if( curChar == '\n' || curChar=='\r' || curChar==' ') 
3792     {
3793       ME_SetSelection(editor, car_pos, car_pos);
3794       RichEditANSIWndProc(editor->hWnd, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM) &default_format);
3795       text_pos=-1;
3796       return 0;
3797     }
3798   }
3799   if (curf_ef == def_ef)
3800   {
3801     cur_prefx = 0;
3802     prefx_cnt = (sizeof(prefixes)/sizeof(struct prefix_s))-1;
3803     while (cur_prefx<=prefx_cnt) 
3804     {
3805       if (text_pos == -1) 
3806       {
3807         ft.lpstrText = prefixes[cur_prefx].text;
3808         URLmin=max(0,(car_pos-prefixes[cur_prefx].length));
3809         URLmax=max(0, car_pos);
3810         if ((car_pos == 0) && (ME_GetTextLength(editor) != 0))
3811         {
3812         URLmax = ME_GetTextLength(editor)+1;
3813         }
3814         ft.chrg.cpMin = URLmin;
3815         ft.chrg.cpMax = URLmax;
3816         text_pos=RichEditANSIWndProc(editor->hWnd, EM_FINDTEXT, FR_DOWN, (LPARAM)&ft);   
3817         cur_prefx++;
3818       }
3819       if (text_pos != -1) 
3820       {
3821         ME_SetCharFormat(editor, text_pos, (URLmax-text_pos), &link);
3822         ME_RewrapRepaint(editor);
3823         break;
3824       }
3825     }
3826   }
3827   return 0;
3828 }
3829
3830
3831 static BOOL isurlspecial(WCHAR c)
3832 {
3833   static const WCHAR special_chars[] = {'.','/','%','@','*','|','\\','+','#',0};
3834   return strchrW( special_chars, c ) != NULL;
3835 }
3836
3837 /**
3838  * This proc takes a selection, and scans it forward in order to select the span
3839  * of a possible URL candidate. A possible URL candidate must start with isalnum
3840  * or one of the following special characters: *|/\+%#@ and must consist entirely
3841  * of the characters allowed to start the URL, plus : (colon) which may occur
3842  * at most once, and not at either end.
3843  *
3844  * sel_max == -1 indicates scan to end of text.
3845  */
3846 BOOL ME_FindNextURLCandidate(ME_TextEditor *editor, int sel_min, int sel_max,
3847         int * candidate_min, int * candidate_max)
3848 {
3849   ME_DisplayItem * item;
3850   ME_DisplayItem * para;
3851   int nStart;
3852   BOOL foundColon = FALSE;
3853   WCHAR lastAcceptedChar = '\0';
3854
3855   TRACE("sel_min = %d sel_max = %d\n", sel_min, sel_max);
3856
3857   *candidate_min = *candidate_max = -1;
3858   item = ME_FindItemAtOffset(editor, diRun, sel_min, &nStart);
3859   if (!item) return FALSE;
3860   TRACE("nStart = %d\n", nStart);
3861   para = ME_GetParagraph(item);
3862   if (sel_max == -1) sel_max = ME_GetTextLength(editor);
3863   while (item && para->member.para.nCharOfs + item->member.run.nCharOfs + nStart < sel_max)
3864   {
3865     ME_DisplayItem * next_item;
3866
3867     if (!(item->member.run.nFlags & MERF_ENDPARA)) {
3868       /* Find start of candidate */
3869       if (*candidate_min == -1) {
3870         while (nStart < ME_StrLen(item->member.run.strText) &&
3871                 !(isalnumW(item->member.run.strText->szData[nStart]) ||
3872                   isurlspecial(item->member.run.strText->szData[nStart]))) {
3873           nStart++;
3874         }
3875         if (nStart < ME_StrLen(item->member.run.strText) &&
3876                 (isalnumW(item->member.run.strText->szData[nStart]) ||
3877                  isurlspecial(item->member.run.strText->szData[nStart]))) {
3878           *candidate_min = para->member.para.nCharOfs + item->member.run.nCharOfs + nStart;
3879           lastAcceptedChar = item->member.run.strText->szData[nStart];
3880           nStart++;
3881         }
3882       }
3883
3884       /* Find end of candidate */
3885       if (*candidate_min >= 0) {
3886         while (nStart < ME_StrLen(item->member.run.strText) &&
3887                 (isalnumW(item->member.run.strText->szData[nStart]) ||
3888                  isurlspecial(item->member.run.strText->szData[nStart]) ||
3889                  (!foundColon && item->member.run.strText->szData[nStart] == ':') )) {
3890           if (item->member.run.strText->szData[nStart] == ':') foundColon = TRUE;
3891           lastAcceptedChar = item->member.run.strText->szData[nStart];
3892           nStart++;
3893         }
3894         if (nStart < ME_StrLen(item->member.run.strText) &&
3895                 !(isalnumW(item->member.run.strText->szData[nStart]) ||
3896                  isurlspecial(item->member.run.strText->szData[nStart]) )) {
3897           *candidate_max = para->member.para.nCharOfs + item->member.run.nCharOfs + nStart;
3898           nStart++;
3899           if (lastAcceptedChar == ':') (*candidate_max)--;
3900           return TRUE;
3901         }
3902       }
3903     } else {
3904       /* End of paragraph: skip it if before candidate span, or terminates
3905          current active span */
3906       if (*candidate_min >= 0) {
3907         *candidate_max = para->member.para.nCharOfs + item->member.run.nCharOfs;
3908         if (lastAcceptedChar == ':') (*candidate_max)--;
3909         return TRUE;
3910       }
3911     }
3912
3913     /* Reaching this point means no span was found, so get next span */
3914     next_item = ME_FindItemFwd(item, diRun);
3915     if (!next_item) {
3916       if (*candidate_min >= 0) {
3917         /* There are no further runs, so take end of text as end of candidate */
3918         *candidate_max = para->member.para.nCharOfs + item->member.run.nCharOfs + nStart;
3919         if (lastAcceptedChar == ':') (*candidate_max)--;
3920         return TRUE;
3921       }
3922     }
3923     item = next_item;
3924     para = ME_GetParagraph(item);
3925     nStart = 0;
3926   }
3927
3928   if (item) {
3929     if (*candidate_min >= 0) {
3930       /* There are no further runs, so take end of text as end of candidate */
3931       *candidate_max = para->member.para.nCharOfs + item->member.run.nCharOfs + nStart;
3932       if (lastAcceptedChar == ':') (*candidate_max)--;
3933       return TRUE;
3934     }
3935   }
3936   return FALSE;
3937 }
3938
3939 /**
3940  * This proc evaluates the selection and returns TRUE if it can be considered an URL
3941  */
3942 BOOL ME_IsCandidateAnURL(ME_TextEditor *editor, int sel_min, int sel_max)
3943 {
3944   struct prefix_s {
3945     const char *text;
3946     int length;
3947   } prefixes[12] = {
3948     /* Code below depends on these being in decreasing length order! */
3949     {"prospero:", 10},
3950     {"telnet:", 8},
3951     {"gopher:", 8},
3952     {"mailto:", 8},
3953     {"https:", 7},
3954     {"file:", 6},
3955     {"news:", 6},
3956     {"wais:", 6},
3957     {"nntp:", 6},
3958     {"http:", 5},
3959     {"www.", 5},
3960     {"ftp:", 5},
3961   };
3962   LPWSTR bufferW = NULL;
3963   WCHAR bufW[32];
3964   int i;
3965
3966   if (sel_max == -1) sel_max = ME_GetTextLength(editor);
3967   assert(sel_min <= sel_max);
3968   for (i = 0; i < sizeof(prefixes) / sizeof(struct prefix_s); i++)
3969   {
3970     if (sel_max - sel_min < prefixes[i].length) continue;
3971     if (bufferW == NULL) {
3972       bufferW = (LPWSTR)heap_alloc((sel_max - sel_min + 1) * sizeof(WCHAR));
3973     }
3974     ME_GetTextW(editor, bufferW, sel_min, min(sel_max - sel_min, strlen(prefixes[i].text)), 0);
3975     MultiByteToWideChar(CP_ACP, 0, prefixes[i].text, -1, bufW, 32);
3976     if (!lstrcmpW(bufW, bufferW))
3977     {
3978       heap_free(bufferW);
3979       return TRUE;
3980     }
3981   }
3982   heap_free(bufferW);
3983   return FALSE;
3984 }
3985
3986 /**
3987  * This proc walks through the indicated selection and evaluates whether each
3988  * section identified by ME_FindNextURLCandidate and in-between sections have
3989  * their proper CFE_LINK attributes set or unset. If the CFE_LINK attribute is
3990  * not what it is supposed to be, this proc sets or unsets it as appropriate.
3991  *
3992  * Returns TRUE if at least one section was modified.
3993  */
3994 BOOL ME_UpdateLinkAttribute(ME_TextEditor *editor, int sel_min, int sel_max)
3995 {
3996   BOOL modified = FALSE;
3997   int cMin, cMax;
3998
3999   if (sel_max == -1) sel_max = ME_GetTextLength(editor);
4000   do
4001   {
4002     int beforeURL[2];
4003     int inURL[2];
4004     CHARFORMAT2W link;
4005
4006     if (ME_FindNextURLCandidate(editor, sel_min, sel_max, &cMin, &cMax))
4007     {
4008       /* Section before candidate is not an URL */
4009       beforeURL[0] = sel_min;
4010       beforeURL[1] = cMin;
4011
4012       if (ME_IsCandidateAnURL(editor, cMin, cMax))
4013       {
4014         inURL[0] = cMin; inURL[1] = cMax;
4015       }
4016       else
4017       {
4018         beforeURL[1] = cMax;
4019         inURL[0] = inURL[1] = -1;
4020       }
4021       sel_min = cMax;
4022     }
4023     else
4024     {
4025       /* No more candidates until end of selection */
4026       beforeURL[0] = sel_min;
4027       beforeURL[1] = sel_max;
4028       inURL[0] = inURL[1] = -1;
4029       sel_min = sel_max;
4030     }
4031
4032     if (beforeURL[0] < beforeURL[1])
4033     {
4034       /* CFE_LINK effect should be consistently unset */
4035       link.cbSize = sizeof(link);
4036       ME_GetCharFormat(editor, beforeURL[0], beforeURL[1], &link);
4037       if (!(link.dwMask & CFM_LINK) || (link.dwEffects & CFE_LINK))
4038       {
4039         /* CFE_LINK must be unset from this range */
4040         memset(&link, 0, sizeof(CHARFORMAT2W));
4041         link.cbSize = sizeof(link);
4042         link.dwMask = CFM_LINK;
4043         link.dwEffects = 0;
4044         ME_SetCharFormat(editor, beforeURL[0], beforeURL[1] - beforeURL[0], &link);
4045         modified = TRUE;
4046       }
4047     }
4048     if (inURL[0] < inURL[1])
4049     {
4050       /* CFE_LINK effect should be consistently set */
4051       link.cbSize = sizeof(link);
4052       ME_GetCharFormat(editor, inURL[0], inURL[1], &link);
4053       if (!(link.dwMask & CFM_LINK) || !(link.dwEffects & CFE_LINK))
4054       {
4055         /* CFE_LINK must be set on this range */
4056         memset(&link, 0, sizeof(CHARFORMAT2W));
4057         link.cbSize = sizeof(link);
4058         link.dwMask = CFM_LINK;
4059         link.dwEffects = CFE_LINK;
4060         ME_SetCharFormat(editor, inURL[0], inURL[1] - inURL[0], &link);
4061         modified = TRUE;
4062       }
4063     }
4064   } while (sel_min < sel_max);
4065   return modified;
4066 }
4067
4068 void ME_UpdateSelectionLinkAttribute(ME_TextEditor *editor)
4069 {
4070   ME_DisplayItem * startPara, * endPara;
4071   ME_DisplayItem * item;
4072   int dummy;
4073   int from, to;
4074
4075   ME_GetSelection(editor, &from, &to);
4076   if (from > to) from ^= to, to ^=from, from ^= to;
4077   startPara = NULL; endPara = NULL;
4078
4079   /* Find paragraph previous to the one that contains start cursor */
4080   item = ME_FindItemAtOffset(editor, diRun, from, &dummy);
4081   if (item) {
4082     startPara = ME_FindItemBack(item, diParagraph);
4083     item = ME_FindItemBack(startPara, diParagraph);
4084     if (item) startPara = item;
4085   }
4086
4087   /* Find paragraph that contains end cursor */
4088   item = ME_FindItemAtOffset(editor, diRun, to, &dummy);
4089   if (item) {
4090     endPara = ME_FindItemFwd(item, diParagraph);
4091   }
4092
4093   if (startPara && endPara) {
4094     ME_UpdateLinkAttribute(editor,
4095       startPara->member.para.nCharOfs,
4096       endPara->member.para.nCharOfs);
4097   } else if (startPara) {
4098     ME_UpdateLinkAttribute(editor,
4099       startPara->member.para.nCharOfs,
4100       -1);
4101   }
4102 }