]> git.lyx.org Git - lyx.git/blob - src/text.C
Other small Backspace() fix in text.C and Undo/Redo for insets
[lyx.git] / src / text.C
1 /* This file is part of
2  * ====================================================== 
3  * 
4  *           LyX, The Document Processor
5  *       
6  *           Copyright 1995 Matthias Ettrich
7  *           Copyright 1995-2000 The LyX Team.
8  *
9  * ====================================================== */
10
11 #include <config.h>
12 #include <cstdlib>
13 #include <cctype>
14
15 #ifdef __GNUG__
16 #pragma implementation "table.h"
17 #endif
18
19 #include "layout.h"
20 #include "lyxparagraph.h"
21 #include "lyxtext.h"
22 #include "support/textutils.h"
23 #include "insets/insetbib.h"
24 #include "lyx_gui_misc.h"
25 #include "gettext.h"
26 #include "bufferparams.h"
27 #include "buffer.h"
28 #include "minibuffer.h"
29 #include "debug.h"
30 #include "lyxrc.h"
31 #include "LyXView.h"
32 #include "lyxrow.h"
33 #include "Painter.h"
34 #include "tracer.h"
35
36 using std::max;
37 using std::min;
38 using std::endl;
39
40 static const int LYX_PAPER_MARGIN = 20;
41
42
43 // ale070405
44 extern int bibitemMaxWidth(Painter &, LyXFont const &);
45
46 #define FIX_DOUBLE_SPACE 1
47
48 static int iso885968x[] = {
49         0xbc,   // 0xa8 = fathatan
50         0xbd,   // 0xa9 = dammatan
51         0xbe,   // 0xaa = kasratan
52         0xdb,   // 0xab = fatha
53         0xdc,   // 0xac = damma
54         0xdd,   // 0xad = kasra
55         0xde,   // 0xae = shadda
56         0xdf,   // 0xaf = sukun
57
58         0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0xb0-0xbf
59
60         0,      // 0xc0 
61         0xc1,   // 0xc1 = hamza
62         0xc2,   // 0xc2 = ligature madda
63         0xc3,   // 0xc3 = ligature hamza on alef
64         0xc4,   // 0xc4 = ligature hamza on waw
65         0xc5,   // 0xc5 = ligature hamza under alef
66         0xc0,   // 0xc6 = ligature hamza on ya 
67         0xc7,   // 0xc7 = alef
68         0xeb,   // 0xc8 = baa 
69         0xc9,   // 0xc9 = taa marbuta
70         0xec,   // 0xca = taa
71         0xed,   // 0xcb = thaa
72         0xee,   // 0xcc = jeem
73         0xef,   // 0xcd = haa
74         0xf0,   // 0xce = khaa
75         0xcf,   // 0xcf = dal
76
77         0xd0,   // 0xd0 = thal
78         0xd1,   // 0xd1 = ra
79         0xd2,   // 0xd2 = zain
80         0xf1,   // 0xd3 = seen
81         0xf2,   // 0xd4 = sheen
82         0xf3,   // 0xd5 = sad
83         0xf4,   // 0xd6 = dad
84         0xd7,   // 0xd7 = tah
85         0xd8,   // 0xd8 = zah
86         0xf5,   // 0xd9 = ain
87         0xf6,   // 0xda = ghain
88         0,0,0,0,0, // 0xdb- 0xdf
89
90         0,      // 0xe0
91         0xf7,   // 0xe1 = fa
92         0xf8,   // 0xe2 = qaf
93         0xf9,   // 0xe3 = kaf
94         0xfa,   // 0xe4 = lam
95         0xfb,   // 0xe5 = meem
96         0xfc,   // 0xe6 = noon
97         0xfd,   // 0xe7 = ha
98         0xe8,   // 0xe8 = waw
99         0xe9,   // 0xe9 = alef maksura
100         0xfe    // 0xea = ya
101 };
102
103 bool is_arabic(unsigned char c)
104 {
105         return 0xa8 <= c && c <= 0xea && iso885968x[c-0xa8];
106 }
107
108 unsigned char LyXText::TransformChar(unsigned char c, Letter_Form form) const
109 {
110         if (is_arabic(c) && 
111             (form == FORM_INITIAL || form == FORM_MEDIAL) )
112                 return iso885968x[c-0xa8];
113         else
114                 return c;
115 }
116
117 unsigned char LyXText::TransformChar(unsigned char c, LyXParagraph * par,
118                         LyXParagraph::size_type pos) const
119 {
120         if (!is_arabic(c))
121                 return c;
122
123         bool not_first = (pos > 0 && is_arabic(par->GetChar(pos-1)));
124         if (pos < par->Last()-1 && is_arabic(par->GetChar(pos+1)))
125                 if (not_first)
126                         return TransformChar(c,FORM_MEDIAL);
127                 else
128                         return TransformChar(c,FORM_INITIAL);
129         else
130                 if (not_first)
131                         return TransformChar(c,FORM_FINAL);
132                 else
133                         return TransformChar(c,FORM_ISOLATED);
134 }
135
136 // This is the comments that some of the warnings below refers to.
137 // There are some issues in this file and I don't think they are
138 // really related to the FIX_DOUBLE_SPACE patch. I'd rather think that
139 // this is a problem that has been here almost from day one and that a
140 // larger userbase with differenct access patters triggers the bad
141 // behaviour. (segfaults.) What I think happen is: In several places
142 // we store the paragraph in the current cursor and then moves the
143 // cursor. This movement of the cursor will delete paragraph at the
144 // old position if it is now empty. This will make the temporary
145 // pointer to the old cursor paragraph invalid and dangerous to use.
146 // And is some cases this will trigger a segfault. I have marked some
147 // of the cases where this happens with a warning, but I am sure there
148 // are others in this file and in text2.C. There is also a note in
149 // Delete() that you should read. In Delete I store the paragraph->id
150 // instead of a pointer to the paragraph. I am pretty sure this faulty
151 // use of temporary pointers to paragraphs that might have gotten
152 // invalidated (through a cursor movement) before they are used, are
153 // the cause of the strange crashes we get reported often.
154 //
155 // It is very tiresom to change this code, especially when it is as
156 // hard to read as it is. Help to fix all the cases where this is done
157 // would be greately appreciated.
158 //
159 // Lgb
160
161 int LyXText::SingleWidth(LyXParagraph * par,
162                          LyXParagraph::size_type pos) const
163 {
164         char c = par->GetChar(pos);
165         return SingleWidth(par, pos, c);
166 }
167
168
169 int LyXText::SingleWidth(LyXParagraph * par,
170                          LyXParagraph::size_type pos, char c) const
171 {
172         LyXFont font = GetFont(par, pos);
173
174         // The most common case is handled first (Asger)
175         if (IsPrintable(c)) {
176                 if (lyxrc.rtl_support && lyxrc.font_norm == "iso8859-6.8x")
177                         c = TransformChar(c, par, pos);
178                 return font.width(c);
179
180         } else if (IsHfillChar(c)) {
181                 return 3;       /* Because of the representation
182                                  * as vertical lines */
183         } else if (c == LyXParagraph::META_FOOTNOTE ||
184                    c == LyXParagraph::META_MARGIN ||
185                    c == LyXParagraph::META_FIG ||
186                    c == LyXParagraph::META_TAB ||
187                    c == LyXParagraph::META_WIDE_FIG ||
188                    c == LyXParagraph::META_WIDE_TAB ||
189                    c == LyXParagraph::META_ALGORITHM) {
190                 string fs;
191                 switch (c) {
192                 case LyXParagraph::META_MARGIN:
193                         fs = "margin";
194                         break;
195                 case LyXParagraph::META_FIG:
196                         fs = "fig";
197                         break;
198                 case LyXParagraph::META_TAB:
199                         fs = "tab";
200                         break;
201                 case LyXParagraph::META_ALGORITHM:
202                         fs = "alg";
203                         break;
204                 case LyXParagraph::META_WIDE_FIG:
205                         fs = "wide-fig";
206                         break;
207                 case LyXParagraph::META_WIDE_TAB:
208                         fs = "wide-tab";
209                         break;
210                 case LyXParagraph::META_FOOTNOTE:
211                         fs = "foot";
212                         break;
213                 }
214                 font.decSize();
215                 font.decSize();
216                 return font.stringWidth(fs);
217         } else if (c == LyXParagraph::META_INSET) {
218                 Inset * tmpinset= par->GetInset(pos);
219                 if (tmpinset)
220                         return par->GetInset(pos)->width(owner_->painter(),
221                                                          font);
222                 else
223                         return 0;
224
225         } else if (IsSeparatorChar(c))
226                 c = ' ';
227         else if (IsNewlineChar(c))
228                 c = 'n';
229         return font.width(c);
230 }
231
232
233 // Returns the paragraph position of the last character in the specified row
234 LyXParagraph::size_type LyXText::RowLast(Row const * row) const
235 {
236         if (row->next == 0)
237                 return row->par->Last() - 1;
238         else if (row->next->par != row->par) 
239                 return row->par->Last() - 1;
240         else 
241                 return row->next->pos - 1;
242 }
243
244
245
246
247
248 void LyXText::ComputeBidiTables(Row * row) const
249 {
250
251         if (!lyxrc.rtl_support) {
252                 bidi_start = -1;
253                 return;
254         }
255         LyXParagraph::size_type last = RowLast(row);
256         bidi_start = row->pos;
257
258         if (bidi_start > last) {
259                 bidi_start = -1;
260                 return;
261         }
262
263         if (last + 2 - bidi_start >
264             static_cast<LyXParagraph::size_type>(log2vis_list.size())) {
265                 LyXParagraph::size_type new_size = 
266                         (last + 2 - bidi_start < 500) ?
267                         500 : 2 * (last + 2 - bidi_start);
268                 log2vis_list.resize(new_size);
269                 vis2log_list.resize(new_size);
270         }
271
272         vis2log_list[last + 1 - bidi_start] = -1;
273         log2vis_list[last + 1 - bidi_start] = -1;
274
275         LyXParagraph::size_type main_body = BeginningOfMainBody(row->par);
276         if (main_body > 0 && row->pos < main_body - 1 && main_body - 1 <= last
277             && row->par->IsLineSeparator(main_body - 1)) {
278                 // This is needed in case there is a direction change in
279                 // the label which is continued into the main body
280                 if (row->par->getParDirection() == LYX_DIR_LEFT_TO_RIGHT) {
281                         ComputeBidiTablesFromTo(row, bidi_start,
282                                                 main_body - 2, 0);
283                         log2vis_list[main_body - 1 - bidi_start] =
284                                 main_body - 1;
285                         vis2log_list[main_body - 1 - bidi_start] =
286                                 main_body - 1;
287                         if (main_body <= last)
288                                 ComputeBidiTablesFromTo(row,
289                                                         main_body,last, 0);
290                 } else {
291                         ComputeBidiTablesFromTo(row, bidi_start,
292                                                 main_body - 2,
293                                                 last - main_body + 2);
294                         log2vis_list[main_body - 1 - bidi_start] =
295                                 last - main_body + 1 + bidi_start;
296                         vis2log_list[last - main_body + 1 - bidi_start] =
297                                 main_body - 1;
298                         if (main_body <= last)
299                                 ComputeBidiTablesFromTo(row, main_body,
300                                                         last, -main_body);
301                 }
302         } else
303                 ComputeBidiTablesFromTo(row, bidi_start, last, 0);
304 }
305
306
307 void LyXText::ComputeBidiTablesFromTo(Row * row,
308                                       LyXParagraph::size_type from,
309                                       LyXParagraph::size_type to,
310                                       LyXParagraph::size_type offset) const
311 {
312         LyXParagraph::size_type vpos, old_lpos, stack[2];
313         LyXDirection par_direction = row->par->getParDirection();
314         LyXDirection direction = par_direction;
315         LyXParagraph::size_type lpos = from;
316         int level = 0;
317
318         while (lpos <= to) {
319                 if (row->par->getLetterDirection(lpos) == direction) {
320                         log2vis_list[lpos - bidi_start] = direction;
321                         ++lpos;
322                 } else {
323                         if (level == 0 ||
324                             (level == 1 && direction == LYX_DIR_RIGHT_TO_LEFT
325                              && row->par->getFont(lpos).isRightToLeft()
326                              && row->par->getFont(lpos).latex() == LyXFont::ON
327                              ) ) {
328                                 // The last check is needed when the
329                                 // char is a space
330                                 stack[level++] = lpos;
331                         } else {
332                                 old_lpos = stack[--level];
333                                 log2vis_list[old_lpos - bidi_start] = 
334                                         log2vis_list[lpos - bidi_start] =
335                                         (old_lpos - lpos) * direction;
336                                 ++lpos;
337                         }
338                         direction = static_cast<LyXDirection>(-direction);
339                 }
340         }
341
342         while (level > 0) {
343                 old_lpos = stack[--level];
344                 log2vis_list[old_lpos - bidi_start] =
345                         (old_lpos - (to + 1)) * direction; 
346                 direction = static_cast<LyXDirection>(-direction);
347         }
348
349         vpos = (par_direction == LYX_DIR_LEFT_TO_RIGHT)
350                 ? from - 1 : to + 1;
351         vpos += offset;
352         for (lpos = from; lpos <= to; ++lpos) {
353                 vpos += log2vis_list[lpos - bidi_start];
354                 vis2log_list[vpos - bidi_start] = lpos;
355                 log2vis_list[lpos - bidi_start] = vpos;
356         }
357 }
358
359
360 void LyXText::draw(Row const * row,
361                    LyXParagraph::size_type & vpos,
362                    int offset, float & x)
363 {
364         Painter & pain = owner_->painter();
365         
366         LyXParagraph::size_type pos = vis2log(vpos);
367         char c = row->par->GetChar(pos);
368
369         if (IsNewlineChar(c)) {
370                 ++vpos;
371                 // Draw end-of-line marker
372                 LyXFont font = GetFont(row->par, pos);
373                 int wid = font.width('n');
374                 int asc = font.maxAscent();
375                 int y = offset + row->baseline;
376                 int xp[3], yp[3];
377                 
378                 if (row->par->getLetterDirection(pos) == LYX_DIR_LEFT_TO_RIGHT) {
379                         xp[0] = int(x + wid * 0.375);
380                         yp[0] = int(y - 0.875 * asc * 0.75);
381                         
382                         xp[1] = int(x);
383                         yp[1] = int(y - 0.500 * asc * 0.75);
384                         
385                         xp[2] = int(x + wid * 0.375);
386                         yp[2] = int(y - 0.125 * asc * 0.75);
387                         
388                         pain.lines(xp, yp, 3, LColor::eolmarker);
389                         
390                         xp[0] = int(x);
391                         yp[0] = int(y - 0.500 * asc * 0.75);
392                         
393                         xp[1] = int(x + wid);
394                         yp[1] = int(y - 0.500 * asc * 0.75);
395                         
396                         xp[2] = int(x + wid);
397                         yp[2] = int(y - asc * 0.75);
398                         
399                         pain.lines(xp, yp, 3, LColor::eolmarker);
400                 } else {
401                         xp[0] = int(x + wid * 0.625);
402                         yp[0] = int(y - 0.875 * asc * 0.75);
403                         
404                         xp[1] = int(x + wid);
405                         yp[1] = int(y - 0.500 * asc * 0.75);
406                         
407                         xp[2] = int(x + wid * 0.625);
408                         yp[2] = int(y - 0.125 * asc * 0.75);
409                         
410                         pain.lines(xp, yp, 3, LColor::eolmarker);
411                         
412                         xp[0] = int(x + wid);
413                         yp[0] = int(y - 0.500 * asc * 0.75);
414                         
415                         xp[1] = int(x);
416                         yp[1] = int(y - 0.500 * asc * 0.75);
417                         
418                         xp[2] = int(x);
419                         yp[2] = int(y - asc * 0.75);
420                         
421                         pain.lines(xp, yp, 3, LColor::eolmarker);
422                 }
423                 x += wid;
424                 return;
425         }
426
427         LyXFont font = GetFont(row->par, pos);
428         LyXFont font2 = font;
429
430         if (c == LyXParagraph::META_FOOTNOTE
431             || c == LyXParagraph::META_MARGIN
432             || c == LyXParagraph::META_FIG
433             || c == LyXParagraph::META_TAB
434             || c == LyXParagraph::META_WIDE_FIG
435             || c == LyXParagraph::META_WIDE_TAB
436             || c == LyXParagraph::META_ALGORITHM) {
437                 string fs;
438                 switch (c) {
439                 case LyXParagraph::META_MARGIN:
440                         fs = "margin";
441                         // Draw a sign at the left margin!
442                         owner_->painter()
443                                 .text((LYX_PAPER_MARGIN - font.width('!'))/2,
444                                       offset + row->baseline, "!", 1, font);
445                         break;
446                 case LyXParagraph::META_FIG:
447                         fs = "fig";
448                         break;
449                 case LyXParagraph::META_TAB:
450                         fs = "tab";
451                         break;
452                 case LyXParagraph::META_ALGORITHM:
453                         fs = "alg";
454                         break;
455                 case LyXParagraph::META_WIDE_FIG:
456                         fs = "wide-fig";
457                         break;
458                 case LyXParagraph::META_WIDE_TAB:
459                         fs = "wide-tab";
460                         break;
461                 case LyXParagraph::META_FOOTNOTE:
462                         fs = "foot";
463                         break;
464                 }
465                 font.decSize();
466                 font.decSize();
467           
468                 // calculate the position of the footnotemark
469                 int y = (row->baseline - font2.maxAscent() 
470                          + font.maxAscent());
471           
472                 font.setColor(LColor::footnote);
473
474                 float tmpx = x;
475
476                 // draw it and set new x position
477                 
478                 pain.text(int(x), offset + y, fs, font);
479                 x += pain.width(fs, font);
480                 pain.line(int(tmpx), offset + row->baseline,
481                           int(x), offset + row->baseline,
482                           LColor::footnote);
483
484                 ++vpos;
485                 return;
486         } else if (c == LyXParagraph::META_INSET) {
487                 Inset * tmpinset = row->par->GetInset(pos);
488                 if (tmpinset) {
489                         tmpinset->draw(owner_->painter(), font,
490                                        offset + row->baseline, x);
491                 }
492                 ++vpos;
493                 return;
494         }
495
496         /* usual characters, no insets */
497
498         // Collect character that we can draw in one command
499
500         // This is dirty, but fast. Notice that it will never be too small.
501         // For the record, I'll note that Microsoft Word has a limit
502         // of 768 here. We have none :-) (Asger)
503         // Ok. I am the first to admit that the use of std::string will be
504         // a tiny bit slower than using a POD char array. However, I claim
505         // that this slowdown is so small that it is close to inperceptive.
506         // So IMHO we should go with the easier and clearer implementation.
507         // And even if 1024 is a large number here it might overflow, string
508         // will only overflow if the machine is out of memory...
509         bool do_transform = (lyxrc.rtl_support && lyxrc.font_norm == "iso8859-6.8x");
510         if (do_transform)
511                 c = TransformChar(c, row->par, pos);
512         static string textstring;
513         textstring = c;
514         ++vpos;
515
516         LyXParagraph::size_type last = RowLast(row);
517         
518         while (vpos <= last &&
519                (pos = vis2log(vpos)) >= 0
520                && static_cast<unsigned char>(c = row->par->GetChar(pos)) > ' '
521                && font2 == GetFont(row->par, pos)) {
522                 if (do_transform)
523                         c = TransformChar(c, row->par, pos);
524                 textstring += c;
525                 ++vpos;
526         }
527         float tmpx = x;
528
529         // Draw text and set the new x position
530         pain.text(int(x), offset + row->baseline, textstring, font);
531         x += pain.width(textstring, font);
532         
533         // what about underbars?
534         if (font.underbar() == LyXFont::ON && font.latex() != LyXFont::ON) {
535                 pain.line(tmpx, offset + row->baseline + 2,
536                           x, offset + row->baseline + 2);
537                 
538         }
539
540         // If we want ulem.sty support, drawing
541         // routines should go here. (Asger)
542         // Why shouldn't LyXFont::drawText handle it internally?
543 }
544
545
546 // Returns the left beginning of the text. 
547 // This information cannot be taken from the layouts-objekt, because in 
548 // LaTeX the beginning of the text fits in some cases (for example sections)
549 // exactly the label-width.
550 int LyXText::LeftMargin(Row const * row) const
551 {
552         LyXLayout const & layout = textclasslist.Style(parameters->textclass,
553                                                        row->par->GetLayout());
554         
555         string parindent = layout.parindent; 
556         
557         /* table stuff -- begin */ 
558         if (row->par->table)
559                 parindent.clear();
560         /* table stuff -- end */
561         
562         int x = LYX_PAPER_MARGIN;
563         
564         x += textclasslist.TextClass(parameters->textclass)
565                 .defaultfont()
566                 .signedStringWidth(textclasslist
567                                    .TextClass(parameters->textclass)
568                                    .leftmargin());
569         
570         if (row->par->footnoteflag == LyXParagraph::OPEN_FOOTNOTE)  {
571                 LyXFont font(LyXFont::ALL_SANE);
572                 font.setSize(LyXFont::SIZE_SMALL);
573                 x += font.textWidth("Mwide-figM", 10) + LYX_PAPER_MARGIN/2;
574         }
575         
576         // this is the way, LyX handles the LaTeX-Environments.
577         // I have had this idea very late, so it seems to be a
578         // later added hack and this is true
579         if (!row->par->GetDepth()) {
580                 if (!row->par->GetLayout()) {
581                         // find the previous same level paragraph
582                         if (row->par->FirstPhysicalPar()->Previous()) {
583                                 LyXParagraph * newpar = row->par
584                                         ->DepthHook(row->par->GetDepth());
585                                 if (newpar &&
586                                     textclasslist.Style(parameters->textclass,
587                                                         newpar->GetLayout())
588                                     .nextnoindent)
589                                         parindent.clear();
590                         }
591                 }
592         } else {
593                 // find the next level paragraph
594                 
595                 LyXParagraph * newpar = row->par->DepthHook(row->par->GetDepth()-1);
596                 
597                 // make a corresponding row. Needed to call LeftMargin()
598                 
599                 // check wether it is a sufficent paragraph 
600                 if (newpar && newpar->footnoteflag == row->par->footnoteflag
601                     && textclasslist
602                         .Style(parameters->textclass, 
603                                newpar->GetLayout()).isEnvironment()) {
604                         Row dummyrow;
605                         dummyrow.par = newpar;
606                         dummyrow.pos = newpar->Last();
607                         x = LeftMargin(&dummyrow);
608                 } else {
609                         // this is no longer an error, because this function
610                         // is used to clear impossible depths after changing
611                         // a layout. Since there is always a redo,
612                         // LeftMargin() is always called
613                         row->par->FirstPhysicalPar()->depth = 0;
614                 }
615                 
616                 if (newpar && !row->par->GetLayout()) {
617                         if (newpar->FirstPhysicalPar()->noindent)
618                                 parindent.clear();
619                         else
620                                 parindent = textclasslist
621                                         .Style(parameters->textclass, 
622                                                newpar->GetLayout()).parindent;
623                 }
624                 
625         }
626         
627         LyXFont labelfont = GetFont(row->par, -2);
628         switch (layout.margintype) {
629         case MARGIN_DYNAMIC:
630                 if (!layout.leftmargin.empty()) {
631                         x += textclasslist
632                                 .TextClass(parameters->textclass)
633                                 .defaultfont()
634                                 .signedStringWidth(layout.leftmargin);
635                 }
636                 if (!row->par->GetLabestring().empty()) {
637                         x += labelfont.signedStringWidth(layout.labelindent);
638                         x += labelfont.stringWidth(row->par->GetLabestring());
639                         x += labelfont.stringWidth(layout.labelsep);
640                 }
641                 break;
642         case MARGIN_MANUAL:
643                 x += labelfont.signedStringWidth(layout.labelindent);
644                 if (row->pos >= BeginningOfMainBody(row->par)) {
645                         if (!row->par->GetLabelWidthString().empty()) {
646                                 x += labelfont
647                                         .stringWidth(row->par
648                                                      ->GetLabelWidthString());
649                                 x += labelfont.stringWidth(layout.labelsep);
650                         }
651                 }
652                 break;
653         case MARGIN_STATIC:
654                 x += textclasslist.TextClass(parameters->textclass)
655                         .defaultfont().signedStringWidth(layout.leftmargin) * 4
656                         / (row->par->GetDepth() + 4);
657                 break;
658         case MARGIN_FIRST_DYNAMIC:
659                 if (layout.labeltype == LABEL_MANUAL) {
660                         if (row->pos >= BeginningOfMainBody(row->par)) {
661                                 x += labelfont
662                                         .signedStringWidth(layout.leftmargin);
663                         } else {
664                                 x += labelfont
665                                         .signedStringWidth(layout.labelindent);
666                         }
667                 } else if (row->pos
668                            // Special case to fix problems with
669                            // theorems (JMarc)
670                            || (layout.labeltype == LABEL_STATIC
671                                && layout.latextype == LATEX_ENVIRONMENT
672                                && ! row->par->IsFirstInSequence())) {
673                         x += labelfont.signedStringWidth(layout.leftmargin);
674                 } else if (layout.labeltype != LABEL_TOP_ENVIRONMENT
675                            && layout.labeltype != LABEL_BIBLIO
676                            && layout.labeltype !=
677                            LABEL_CENTERED_TOP_ENVIRONMENT) {
678                         x += labelfont.signedStringWidth(layout.labelindent);
679                         x += labelfont.stringWidth(layout.labelsep);
680                         x += labelfont.stringWidth(row->par->GetLabestring());
681                 } 
682                 break;
683                 
684         case MARGIN_RIGHT_ADDRESS_BOX:
685         {
686                 // ok, a terrible hack. The left margin depends on the widest
687                 // row in this paragraph. Do not care about footnotes, they
688                 // are *NOT* allowed in the LaTeX realisation of this layout.
689                 
690                 // find the first row of this paragraph
691                 Row const * tmprow = row;
692                 while (tmprow->previous && tmprow->previous->par == row->par)
693                         tmprow = tmprow->previous;
694                 
695                 int minfill = tmprow->fill;
696                 while (tmprow->next && tmprow->next->par == row->par) {
697                         tmprow = tmprow->next;
698                         if (tmprow->fill < minfill)
699                                 minfill = tmprow->fill;
700                 }
701                 
702                 x += textclasslist.TextClass(parameters->textclass)
703                         .defaultfont().signedStringWidth(layout.leftmargin);
704                 x += minfill;
705         }
706         break;
707         }
708         if (row->par->pextra_type == LyXParagraph::PEXTRA_INDENT) {
709                 if (!row->par->pextra_widthp.empty()) {
710                         x += paperwidth *
711                                 atoi(row->par->pextra_widthp.c_str()) / 100;
712                 } else if (!row->par->pextra_width.empty()) {
713                         int xx = VSpace(row->par->pextra_width).inPixels(owner_);
714                         
715                         if (xx > paperwidth)
716                                 xx = paperwidth * 80 / 100;
717                         x += xx;
718                 } else { // should not happen
719                         LyXFont font(LyXFont::ALL_SANE);
720                         x += font.stringWidth("XXXXXX");
721                 }
722         }
723         
724         int align; // wrong type
725         if (row->par->FirstPhysicalPar()->align == LYX_ALIGN_LAYOUT)
726                 align = layout.align;
727         else
728                 align = row->par->FirstPhysicalPar()->align;
729         
730         // set the correct parindent
731         if (row->pos == 0) {
732                 if ((layout.labeltype == LABEL_NO_LABEL 
733                      || layout.labeltype == LABEL_TOP_ENVIRONMENT 
734                      || layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT
735                      || (layout.labeltype == LABEL_STATIC
736                          && layout.latextype == LATEX_ENVIRONMENT
737                          && ! row->par->IsFirstInSequence()))
738                     && row->par == row->par->FirstPhysicalPar()
739                     && align == LYX_ALIGN_BLOCK
740                     && !row->par->noindent
741                     && (row->par->layout ||
742                         parameters->paragraph_separation ==
743                         BufferParams::PARSEP_INDENT))
744                         x += textclasslist.TextClass(parameters->textclass)
745                                 .defaultfont().signedStringWidth(parindent);
746                 else if (layout.labeltype == LABEL_BIBLIO) {
747                         // ale970405 Right width for bibitems
748                         x += bibitemMaxWidth(owner_->painter(),
749                                              textclasslist
750                                              .TextClass(parameters
751                                                         ->textclass)
752                                              .defaultfont());
753                 }
754         }
755         return x;
756 }
757     
758    
759 int LyXText::RightMargin(Row const * row) const
760 {
761         LyXLayout const & layout =
762                 textclasslist.Style(parameters->textclass,
763                                     row->par->GetLayout());
764         
765         int x = LYX_PAPER_MARGIN
766                 + textclasslist
767                 .TextClass(parameters->textclass)
768                 .defaultfont()
769                 .signedStringWidth(textclasslist
770                                    .TextClass(parameters->textclass)
771                                    .rightmargin());
772         
773         if (row->par->footnoteflag == LyXParagraph::OPEN_FOOTNOTE)  {
774                 x += LYX_PAPER_MARGIN / 2;
775         }
776         
777         // this is the way, LyX handles the LaTeX-Environments.
778         // I have had this idea very late, so it seems to be a
779         // later added hack and this is true
780         if (row->par->GetDepth()) {
781                 // find the next level paragraph
782                 
783                 LyXParagraph * newpar = row->par;
784                 
785                 do {
786                         newpar = newpar->FirstPhysicalPar()->Previous();
787                         if (newpar) 
788                                 newpar = newpar->FirstPhysicalPar();
789                 } while (newpar && newpar->GetDepth() >= row->par->GetDepth()
790                          && newpar->footnoteflag == row->par->footnoteflag);
791                 
792                 // make a corresponding row. Needed to call LeftMargin()
793                 
794                 // check wether it is a sufficent paragraph
795                 if (newpar && newpar->footnoteflag == row->par->footnoteflag
796                     && textclasslist.Style(parameters->textclass,
797                                            newpar->GetLayout())
798                        .isEnvironment()) {
799                         Row dummyrow;
800                         dummyrow.par = newpar;
801                         dummyrow.pos = 0;
802                         x = RightMargin(&dummyrow);
803                 } else {
804                         // this is no longer an error, because this function
805                         // is used to clear impossible depths after changing
806                         // a layout. Since there is always a redo,
807                         // LeftMargin() is always called
808                         row->par->FirstPhysicalPar()->depth = 0;
809                 }
810         }
811         
812         //lyxerr << "rightmargin: " << layout->rightmargin << endl;
813         x += textclasslist.TextClass(parameters->textclass)
814                 .defaultfont()
815                 .signedStringWidth(layout.rightmargin) * 4
816               / (row->par->GetDepth() + 4);
817         return x;
818 }
819
820
821 int LyXText::LabelEnd (Row const * row) const
822 {
823         if (textclasslist.Style(parameters->textclass,
824                                 row->par->GetLayout()).margintype
825             == MARGIN_MANUAL) {
826                 Row tmprow;
827                 tmprow = *row;
828                 tmprow.pos = row->par->Last();
829                 return LeftMargin(&tmprow);  /* just the beginning 
830                                                 of the main body */
831         } else
832                 return 0;  /* LabelEnd is only needed, if the  
833                               layout fills a flushleft
834                               label. */
835 }
836
837
838 /* table stuff -- begin*/
839 int LyXText::NumberOfCell(LyXParagraph * par,
840                           LyXParagraph::size_type pos) const
841 {
842    int cell = 0;
843    LyXParagraph::size_type tmp_pos = 0;
844    while (tmp_pos < pos) {
845       if (par->IsNewline(tmp_pos))
846          ++cell;
847       ++tmp_pos;
848    }
849    return cell;
850 }
851
852
853 int LyXText::WidthOfCell(LyXParagraph * par,
854                          LyXParagraph::size_type & pos) const
855 {
856    int w = 0;
857    while (pos < par->Last() && !par->IsNewline(pos)) {
858       w += SingleWidth(par, pos);
859       ++pos;
860    }
861    if (par->IsNewline(pos))
862       ++pos;
863    return w;
864 }
865
866
867 bool LyXText::HitInTable(Row * row, int x) const
868 {
869         float tmpx;
870         float fill_separator, fill_hfill, fill_label_hfill;
871         if (!row->par->table)
872                 return false;
873         PrepareToPrint(row, tmpx, fill_separator,
874                        fill_hfill, fill_label_hfill, false);
875         return (x > tmpx && x < tmpx + row->par->table->WidthOfTable());
876 }
877
878
879 bool LyXText::MouseHitInTable(int x, long y) const
880 {
881         Row * row = GetRowNearY(y);
882         return HitInTable(row, x);
883 }
884
885
886 /* table stuff -- end*/
887
888
889 // get the next breakpoint in a given paragraph
890 LyXParagraph::size_type
891 LyXText::NextBreakPoint(Row const * row, int width) const
892 {
893         LyXParagraph * par = row->par;
894         LyXParagraph::size_type pos = row->pos;
895         
896         /* table stuff -- begin*/ 
897         if (par->table) {
898                 while (pos < par->size()
899                        && (!par->IsNewline(pos) 
900                            || !par->table->IsFirstCell(NumberOfCell(par, pos+1)))) {
901                         if (par->GetChar(pos) == LyXParagraph::META_INSET &&
902                             par->GetInset(pos) && par->GetInset(pos)->display()){
903                                 par->GetInset(pos)->display(false);
904                         }
905                         ++pos;
906                 }
907                 return pos;
908         }
909         /* table stuff -- end*/ 
910         
911         // position of the last possible breakpoint 
912         // -1 isn't a suitable value, but a flag
913         LyXParagraph::size_type last_separator = -1;
914         width -= RightMargin(row);
915         
916         LyXParagraph::size_type main_body = BeginningOfMainBody(par);
917         LyXLayout const & layout =
918                 textclasslist.Style(parameters->textclass, par->GetLayout());
919         LyXParagraph::size_type i = pos;
920
921         if (layout.margintype == MARGIN_RIGHT_ADDRESS_BOX) {
922                 /* special code for right address boxes, only newlines count */
923                 while (i < par->Last()) {
924                         if (par->IsNewline(i)) {
925                                 last_separator = i;
926                                 i = par->Last() - 1; // this means break
927                                 //x = width;
928                         } else if (par->GetChar(i) == LyXParagraph::META_INSET &&
929                                    par->GetInset(i) && par->GetInset(i)->display()){
930                                 par->GetInset(i)->display(false);
931                         }
932                         ++i;
933                 }
934         } else {
935                 // Last position is an invariant
936                 LyXParagraph::size_type const last = 
937                         par->Last();
938                 // this is the usual handling
939                 int x = LeftMargin(row);
940                 while (x < width && i < last) {
941                         char c = par->GetChar(i);
942                         if (IsNewlineChar(c)) {
943                                 last_separator = i;
944                                 x = width; // this means break
945                         } else if (c == LyXParagraph::META_INSET &&
946                                    par->GetInset(i) && par->GetInset(i)->display()){
947                                 // check wether a Display() inset is
948                                 // valid here. if not, change it to
949                                 // non-display
950                                 if (layout.isCommand()
951                                     || (layout.labeltype == LABEL_MANUAL
952                                         && i < BeginningOfMainBody(par))){
953                                         // display istn't allowd
954                                         par->GetInset(i)->display(false);
955                                         x += SingleWidth(par, i, c);
956                                 } else {
957                                         // inset is display. So break the line here
958                                         if (i == pos){
959                                                 if (pos < last-1) {
960                                                         last_separator = i;
961                                                         if (IsLineSeparatorChar(par->GetChar(i+1)))
962                                                                 ++last_separator;
963                                                 } else
964                                                         last_separator = last; // to avoid extra rows
965                                         } else
966                                                 last_separator = i - 1;
967                                         x = width;  // this means break
968                                 }
969                         } else  {
970                                 if (IsLineSeparatorChar(c))
971                                         last_separator = i;
972                                 x += SingleWidth(par, i, c);
973                         }
974                         ++i;
975                         if (i == main_body) {
976                                 x += GetFont(par, -2).stringWidth(layout.labelsep);
977                                 if (par->IsLineSeparator(i - 1))
978                                         x-= SingleWidth(par, i - 1);
979                                 int left_margin = LabelEnd(row);
980                                 if (x < left_margin)
981                                         x = left_margin;
982                         }
983                 }
984                 // end of paragraph is always a suitable separator
985                 if (i == last && x < width)
986                         last_separator = i;
987         }
988         
989         // well, if last_separator is still 0, the line isn't breakable. 
990         // don't care and cut simply at the end
991         if (last_separator < 0) {
992                 last_separator = i;
993         }
994         
995         // manual labels cannot be broken in LaTeX, do not care
996         if (main_body && last_separator < main_body)
997                 last_separator = main_body - 1;
998         
999         return last_separator;
1000 }
1001
1002
1003 // returns the minimum space a row needs on the screen in pixel
1004 int LyXText::Fill(Row const * row, int paper_width) const
1005 {
1006         int w, fill;
1007         // get the pure distance
1008         LyXParagraph::size_type last = RowLast(row);
1009         /* table stuff -- begin */
1010         if (row->par->table) {
1011                 // for tables FILL does calculate the widthes of each cell in 
1012                 // the row
1013                 LyXParagraph::size_type pos = row->pos;
1014                 int cell = NumberOfCell(row->par, pos);
1015                 w = 0;
1016                 do {
1017                         row->par->table->SetWidthOfCell(cell,
1018                                                         WidthOfCell(row->par,
1019                                                                     pos));
1020                         ++cell;
1021                 } while (pos <= last && !row->par->table->IsFirstCell(cell));
1022                 // don't forget the very last table cell without characters
1023                 if (cell == row->par->table->GetNumberOfCells() - 1)
1024                         row->par->table->SetWidthOfCell(cell,
1025                                                         WidthOfCell(row->par,
1026                                                                     pos));
1027                 
1028                 return 0; /* width of table cannot be returned since
1029                            * we cannot guarantee its correct value at
1030                            * this point. */ 
1031         }
1032         /* table stuff -- end*/ 
1033                 
1034         // if the row ends with newline, this newline will not be relevant
1035         //if (last >= 0 && row->par->IsNewline(last))
1036         //      --last;
1037         
1038         // if the row ends with a space, this space will not be relevant
1039         if (last >= 0 && row->par->IsLineSeparator(last))
1040                 --last;
1041         
1042         // special handling of the right address boxes
1043         if (textclasslist.Style(parameters->textclass,
1044                                 row->par->GetLayout()).margintype
1045             == MARGIN_RIGHT_ADDRESS_BOX) {
1046                 int tmpfill = row->fill;
1047                 row->fill = 0; // the minfill in MarginLeft()
1048                 w = LeftMargin(row);
1049                 row->fill = tmpfill;
1050         } else
1051                 w = LeftMargin(row);
1052         
1053         LyXLayout const & layout = textclasslist.Style(parameters->textclass,
1054                                                        row->par->GetLayout());
1055         LyXParagraph::size_type main_body = 
1056                 BeginningOfMainBody(row->par);
1057         LyXParagraph::size_type i = row->pos;
1058
1059         while (i <= last) {
1060                 if (main_body > 0 && i == main_body) {
1061                         w += GetFont(row->par, -2).
1062                                 stringWidth(layout.labelsep);
1063                         if (row->par->IsLineSeparator(i - 1))
1064                                 w -= SingleWidth(row->par, i - 1);
1065                         int left_margin = LabelEnd(row);
1066                         if (w < left_margin)
1067                                 w = left_margin;
1068                 }
1069                 w += SingleWidth(row->par, i);
1070                 ++i;
1071         }
1072         if (main_body > 0 && main_body > last) {
1073                 w += GetFont(row->par, -2).stringWidth(layout.labelsep);
1074                 if (last >= 0 && row->par->IsLineSeparator(last))
1075                         w -= SingleWidth(row->par, last);
1076                 int left_margin = LabelEnd(row);
1077                 if (w < left_margin)
1078                         w = left_margin;
1079         }
1080         
1081         fill = paper_width - w - RightMargin(row);
1082         return fill;
1083 }
1084
1085
1086 // returns the minimum space a manual label needs on the screen in pixel
1087 int LyXText::LabelFill(Row const * row) const
1088 {
1089         LyXParagraph::size_type last = BeginningOfMainBody(row->par) - 1;
1090         // -1 because a label ends either with a space that is in the label, 
1091         // or with the beginning of a footnote that is outside the label.
1092
1093         // I don't understand this code in depth, but sometimes "last" is
1094         // less than 0 and this causes a crash. This fix seems to work
1095         // correctly, but I bet the real error is elsewhere.  The bug is
1096         // triggered when you have an open footnote in a paragraph
1097         // environment with a manual label. (Asger)
1098         if (last < 0) last = 0;
1099         
1100         if (row->par->IsLineSeparator(last)) /* a sepearator at this end 
1101                                                 does not count */
1102                 --last;
1103         
1104         int w = 0;
1105         int i = row->pos;
1106         while (i <= last) {
1107                 w += SingleWidth(row->par, i);
1108                 ++i;
1109         }
1110         
1111         int fill = 0;
1112         if (!row->par->labelwidthstring.empty()) {
1113                 fill = GetFont(row->par, -2)
1114                         .stringWidth(row->par->labelwidthstring) - w;
1115         }
1116         
1117         if (fill < 0)
1118                 fill = 0;
1119         
1120         return fill;
1121 }
1122
1123
1124 // returns the number of separators in the specified row. The separator 
1125 // on the very last column doesnt count
1126 int LyXText::NumberOfSeparators(Row const * row) const
1127 {
1128         int last = RowLast(row);
1129         int p = max(row->pos, BeginningOfMainBody(row->par));
1130         int n = 0;
1131         for (; p < last; ++p) {
1132                 if (row->par->IsSeparator(p)) {
1133                         ++n;
1134                 }
1135         }
1136         return n;
1137 }
1138
1139
1140 // returns the number of hfills in the specified row. The LyX-Hfill is
1141 // a LaTeX \hfill so that the hfills at the beginning and at the end were 
1142 // ignored. This is *MUCH* more usefull than not to ignore!
1143 int LyXText::NumberOfHfills(Row const * row) const
1144 {
1145         int last = RowLast(row);
1146         int first = row->pos;
1147         if (first) { /* hfill *DO* count at the beginning 
1148                       * of paragraphs! */
1149                 while(first <= last && row->par->IsHfill(first))
1150                         ++first;
1151         }
1152
1153         first = max(first, BeginningOfMainBody(row->par));
1154         int n = 0;
1155         for (int p = first; p <= last; ++p) { // last, because the end is ignored!
1156                 if (row->par->IsHfill(p)) {
1157                         ++n;
1158                 }
1159         }
1160         return n;
1161 }
1162
1163
1164 // like NumberOfHfills, but only those in the manual label!
1165 int LyXText::NumberOfLabelHfills(Row const * row) const
1166 {
1167         LyXParagraph::size_type last = RowLast(row);
1168         LyXParagraph::size_type first = row->pos;
1169         if (first) { /* hfill *DO* count at the beginning 
1170                       * of paragraphs! */
1171                 while(first < last && row->par->IsHfill(first))
1172                         ++first;
1173         }
1174
1175         last = min(last, BeginningOfMainBody(row->par));
1176         int n = 0;
1177         for (LyXParagraph::size_type p = first;
1178              p < last; ++p) {  // last, because the end is ignored!
1179                 if (row->par->IsHfill(p)) {
1180                         ++n;
1181                 }
1182         }
1183         return n;
1184 }
1185
1186
1187 // returns true, if a expansion is needed.
1188 // Rules are given by LaTeX
1189 bool LyXText::HfillExpansion(Row const * row_ptr,
1190                              LyXParagraph::size_type pos) const
1191 {
1192         // by the way, is it a hfill?
1193         if (!row_ptr->par->IsHfill(pos))
1194                 return false;
1195         
1196         // at the end of a row it does not count
1197         if (pos >= RowLast(row_ptr))
1198                 return false;
1199         
1200         // at the beginning of a row it does not count, if it is not 
1201         // the first row of a paragaph
1202         if (!row_ptr->pos)
1203                 return true;
1204         
1205         // in some labels  it does not count
1206         if (textclasslist.Style(parameters->textclass,
1207                                 row_ptr->par->GetLayout()).margintype
1208             != MARGIN_MANUAL
1209             && pos < BeginningOfMainBody(row_ptr->par))
1210                 return false; 
1211         
1212         // if there is anything between the first char of the row and
1213         // the sepcified position that is not a newline and not a hfill,
1214         // the hfill will count, otherwise not
1215         LyXParagraph::size_type i = row_ptr->pos;
1216         while (i < pos && (row_ptr->par->IsNewline(i)
1217                            || row_ptr->par->IsHfill(i)))
1218                 ++i;
1219         
1220         return i != pos;
1221 }
1222
1223
1224 void LyXText::SetHeightOfRow(Row * row_ptr) const
1225 {
1226     /* get the maximum ascent and the maximum descent */
1227    int asc, desc, pos;
1228    float layoutasc = 0;
1229    float layoutdesc = 0;
1230    float tmptop = 0;
1231    LyXFont tmpfont;
1232    Inset * tmpinset;
1233
1234    /* this must not happen before the currentrow for clear reasons.
1235       so the trick is just to set the current row onto this row */
1236    long unused_y;
1237    GetRow(row_ptr->par, row_ptr->pos, unused_y);
1238
1239    /* ok , let us initialize the maxasc and maxdesc value. 
1240     * This depends in LaTeX of the font of the last character
1241     * in the paragraph. The hack below is necessary because
1242     * of the possibility of open footnotes */
1243
1244    /* Correction: only the fontsize count. The other properties
1245       are taken from the layoutfont. Nicer on the screen :) */
1246    
1247    LyXParagraph * par = row_ptr->par->LastPhysicalPar();
1248    LyXParagraph * firstpar = row_ptr->par->FirstPhysicalPar();
1249    
1250    LyXLayout const & layout = textclasslist.Style(parameters->textclass,
1251                                                   firstpar->GetLayout());
1252    
1253    LyXFont font = GetFont(par, par->Last()-1);
1254    LyXFont::FONT_SIZE size = font.size();
1255    font = GetFont(par, -1);
1256    font.setSize(size);
1257
1258    LyXFont labelfont = GetFont(par, -2);
1259
1260    int maxasc = int(font.maxAscent() *
1261                    layout.spacing.getValue() *
1262                    parameters->spacing.getValue());
1263    int maxdesc = int(font.maxDescent() *
1264                     layout.spacing.getValue() *
1265                     parameters->spacing.getValue());
1266
1267    int pos_end = RowLast(row_ptr);
1268    
1269    int labeladdon = 0;
1270
1271    // Check if any insets are larger
1272    for (pos = row_ptr->pos; pos <= pos_end; ++pos) {
1273       if (row_ptr->par->GetChar(pos) == LyXParagraph::META_INSET) {
1274          tmpfont = GetFont(row_ptr->par, pos);
1275          tmpinset = row_ptr->par->GetInset(pos);
1276          if (tmpinset) {
1277             asc = tmpinset->ascent(owner_->painter(), tmpfont);
1278             desc = tmpinset->descent(owner_->painter(), tmpfont);
1279             if (asc > maxasc) 
1280               maxasc = asc;
1281             if (desc > maxdesc)
1282               maxdesc = desc;
1283          }
1284       }
1285    }
1286
1287    // Check if any custom fonts are larger (Asger)
1288    // This is not completely correct, but we can live with the small,
1289    // cosmetic error for now.
1290    LyXFont::FONT_SIZE maxsize = row_ptr->par->HighestFontInRange(row_ptr->pos,
1291                                                                  pos_end);
1292    if (maxsize > font.size()) {
1293         font.setSize(maxsize);
1294
1295         asc = font.maxAscent();
1296         desc = font.maxDescent();
1297         if (asc > maxasc) 
1298                 maxasc = asc;
1299         if (desc > maxdesc)
1300                 maxdesc = desc;
1301    }
1302
1303    /* table stuff -- begin*/
1304    if (row_ptr->par->table){
1305      // stretch the rows a bit
1306       maxasc += 1;
1307       maxdesc += 1;
1308    }
1309    /* table stuff -- end*/
1310
1311    // This is nicer with box insets:
1312    ++maxasc;
1313    ++maxdesc;
1314
1315    row_ptr->ascent_of_text = maxasc;
1316    
1317    /* is it a top line? */ 
1318    if (row_ptr->pos == 0
1319        && row_ptr->par == firstpar) {
1320       
1321       /* some parksips VERY EASY IMPLEMENTATION */ 
1322       if (parameters->paragraph_separation == BufferParams::PARSEP_SKIP) {
1323          if (layout.isParagraph()
1324              && firstpar->GetDepth() == 0
1325              && firstpar->Previous())
1326             maxasc += parameters->getDefSkip().inPixels(owner_);
1327          else if (firstpar->Previous()
1328                   && textclasslist.Style(parameters->textclass,
1329                            firstpar->Previous()->GetLayout()).isParagraph()
1330                   && firstpar->Previous()->GetDepth() == 0)
1331            // is it right to use defskip here too? (AS)
1332            maxasc += parameters->getDefSkip().inPixels(owner_);
1333       }
1334       
1335       /* the paper margins */ 
1336       if (!row_ptr->par->previous)
1337          maxasc += LYX_PAPER_MARGIN;
1338       
1339       /* add the vertical spaces, that the user added */
1340       if (firstpar->added_space_top.kind() != VSpace::NONE)
1341          maxasc += int(firstpar->added_space_top.inPixels(owner_));
1342       
1343       /* do not forget the DTP-lines! 
1344        * there height depends on the font of the nearest character */
1345       if (firstpar->line_top)
1346          maxasc += 2 * GetFont(firstpar, 0).ascent('x');
1347       
1348       /* and now the pagebreaks */ 
1349       if (firstpar->pagebreak_top)
1350          maxasc += 3 * DefaultHeight();
1351       
1352       /*  this is special code for the chapter, since the label of this
1353        * layout is printed in an extra row */ 
1354       if (layout.labeltype == LABEL_COUNTER_CHAPTER
1355           && parameters->secnumdepth>= 0) {
1356               labeladdon = int(labelfont.maxDescent() *
1357                                   layout.spacing.getValue() *
1358                                   parameters->spacing.getValue())
1359                       + int(labelfont.maxAscent() *
1360                                layout.spacing.getValue() *
1361                                parameters->spacing.getValue());
1362       }
1363       
1364       /* special code for the top label */ 
1365       if ((layout.labeltype == LABEL_TOP_ENVIRONMENT
1366            || layout.labeltype == LABEL_BIBLIO
1367            || layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
1368           && row_ptr->par->IsFirstInSequence()
1369           && !row_ptr->par->GetLabestring().empty()) {
1370          labeladdon = int(
1371                  (labelfont.maxAscent() *
1372                   layout.spacing.getValue() *
1373                   parameters->spacing.getValue())
1374                  +(labelfont.maxDescent() *
1375                    layout.spacing.getValue() *
1376                    parameters->spacing.getValue())
1377                  + layout.topsep * DefaultHeight()
1378                  + layout.labelbottomsep *  DefaultHeight());
1379       }
1380    
1381       /* and now the layout spaces, for example before and after a section, 
1382        * or between the items of a itemize or enumerate environment */ 
1383       
1384       if (!firstpar->pagebreak_top) {
1385          LyXParagraph * prev = row_ptr->par->Previous();
1386          if (prev)
1387             prev = row_ptr->par->DepthHook(row_ptr->par->GetDepth());
1388          if (prev && prev->GetLayout() == firstpar->GetLayout()
1389              && prev->GetDepth() == firstpar->GetDepth()
1390              && prev->GetLabelWidthString() == firstpar->GetLabelWidthString())
1391            {
1392               layoutasc = (layout.itemsep * DefaultHeight());
1393            }
1394          else if (row_ptr->previous) {
1395             tmptop = layout.topsep;
1396             
1397             if (row_ptr->previous->par->GetDepth() >= row_ptr->par->GetDepth())
1398                tmptop-= textclasslist.Style(parameters->textclass, row_ptr->previous->par->GetLayout()).bottomsep;
1399             
1400             if (tmptop > 0)
1401                layoutasc = (tmptop * DefaultHeight());
1402          }
1403          else if (row_ptr->par->line_top){
1404             tmptop = layout.topsep;
1405             
1406             if (tmptop > 0)
1407                layoutasc = (tmptop * DefaultHeight());
1408          }
1409          
1410          prev = row_ptr->par->DepthHook(row_ptr->par->GetDepth()-1);
1411          if (prev)  {
1412             maxasc += int(textclasslist.Style(parameters->textclass,
1413                                          prev->GetLayout()).parsep * DefaultHeight());
1414          }
1415          else {
1416                 if (firstpar->Previous()
1417                     && firstpar->Previous()->GetDepth() == 0
1418                     && firstpar->Previous()->GetLayout() != firstpar->GetLayout()) {
1419                    /* avoid parsep */ 
1420                 }
1421             else if (firstpar->Previous()){
1422                maxasc += int(layout.parsep * DefaultHeight());
1423             }
1424          }
1425       }
1426    }
1427    
1428    /* is it a bottom line? */ 
1429    if (row_ptr->par->ParFromPos(RowLast(row_ptr) + 1) == par
1430        && (!row_ptr->next || row_ptr->next->par != row_ptr->par)) {     
1431           
1432           /* the paper margins */ 
1433           if (!par->next)
1434             maxdesc += LYX_PAPER_MARGIN;
1435         
1436           /* add the vertical spaces, that the user added */
1437           if (firstpar->added_space_bottom.kind() != VSpace::NONE)
1438             maxdesc += int(firstpar->added_space_bottom.inPixels(owner_));
1439           
1440           /* do not forget the DTP-lines! 
1441            * there height depends on the font of the nearest character */
1442           if (firstpar->line_bottom)
1443             maxdesc += 2 * (GetFont(par, par->Last()-1).ascent('x'));
1444           
1445           /* and now the pagebreaks */
1446           if (firstpar->pagebreak_bottom)
1447             maxdesc += 3 * DefaultHeight();
1448           
1449           /* and now the layout spaces, for example before and after a section, 
1450            * or between the items of a itemize or enumerate environment */
1451           if (!firstpar->pagebreak_bottom && row_ptr->par->Next()) {
1452              LyXParagraph * nextpar = row_ptr->par->Next();
1453              LyXParagraph * comparepar = row_ptr->par;
1454              float usual = 0;
1455              float  unusual = 0;
1456              
1457              if (comparepar->GetDepth() > nextpar->GetDepth()) {
1458                 usual = (textclasslist.Style(parameters->textclass, comparepar->GetLayout()).bottomsep * DefaultHeight());
1459                 comparepar = comparepar->DepthHook(nextpar->GetDepth());
1460                 if (comparepar->GetLayout()!= nextpar->GetLayout()
1461                     || nextpar->GetLabelWidthString() != 
1462                         comparepar->GetLabelWidthString())
1463                   unusual = (textclasslist.Style(parameters->textclass, comparepar->GetLayout()).bottomsep * DefaultHeight());
1464                 
1465                 if (unusual > usual)
1466                   layoutdesc = unusual;
1467                 else
1468                   layoutdesc = usual;
1469              }
1470              else if (comparepar->GetDepth() ==  nextpar->GetDepth()) {
1471                 
1472                 if (comparepar->GetLayout()!= nextpar->GetLayout()
1473                     || nextpar->GetLabelWidthString() != 
1474                         comparepar->GetLabelWidthString())
1475                   layoutdesc = int(textclasslist.Style(parameters->textclass, comparepar->GetLayout()).bottomsep * DefaultHeight());
1476              }
1477           }
1478        }
1479    
1480    /* incalculate the layout spaces */ 
1481    maxasc += int(layoutasc * 2 / (2 + firstpar->GetDepth()));
1482    maxdesc += int(layoutdesc * 2 / (2 + firstpar->GetDepth()));
1483
1484    /* table stuff -- begin*/
1485    if (row_ptr->par->table){
1486       maxasc += row_ptr->par->table->
1487         AdditionalHeight(NumberOfCell(row_ptr->par, row_ptr->pos));
1488    }
1489    /* table stuff -- end*/
1490    
1491    /* calculate the new height of the text */ 
1492    height -= row_ptr->height;
1493    
1494    row_ptr->height = maxasc + maxdesc + labeladdon;
1495    row_ptr->baseline = maxasc + labeladdon;
1496    
1497    height += row_ptr->height;
1498 }
1499
1500
1501 /* Appends the implicit specified paragraph behind the specified row,
1502  * start at the implicit given position */
1503 void LyXText::AppendParagraph(Row * row) const
1504 {
1505    bool not_ready = true;
1506    
1507    // The last character position of a paragraph is an invariant so we can 
1508    // safely get it here. (Asger)
1509    int lastposition = row->par->Last();
1510
1511    do {
1512       // Get the next breakpoint
1513       int z = NextBreakPoint(row, paperwidth);
1514       
1515       Row * tmprow = row;
1516
1517       // Insert the new row
1518       if (z < lastposition) {
1519          ++z;
1520          InsertRow(row, row->par, z);
1521          row = row->next;
1522
1523          row->height = 0;
1524       } else
1525          not_ready = false;
1526       
1527       // Set the dimensions of the row
1528       tmprow->fill = Fill(tmprow, paperwidth);
1529       SetHeightOfRow(tmprow);
1530
1531    } while (not_ready);
1532 }
1533
1534
1535 void LyXText::BreakAgain(Row * row) const
1536 {
1537    bool not_ready = true;
1538    
1539    do  {
1540       /* get the next breakpoint */
1541         LyXParagraph::size_type z = 
1542                 NextBreakPoint(row, paperwidth);
1543       Row * tmprow = row;
1544       
1545       if (z < row->par->Last() ) {
1546          if (!row->next || (row->next && row->next->par != row->par)) {
1547                  // insert a new row
1548             ++z;
1549             InsertRow(row, row->par, z);
1550             row = row->next;
1551             row->height = 0;
1552          } else  {
1553             row = row->next;
1554             ++z;
1555             if (row->pos == z)
1556                     not_ready = false;     // the rest will not change
1557             else {
1558                row->pos = z;
1559             }
1560          }
1561       } else {
1562          /* if there are some rows too much, delete them */
1563          /* only if you broke the whole paragraph! */ 
1564          Row * tmprow2 = row;
1565          while (tmprow2->next && tmprow2->next->par == row->par) {
1566             tmprow2 = tmprow2->next;
1567          }
1568          while (tmprow2 != row) {
1569             tmprow2 = tmprow2->previous;
1570             RemoveRow(tmprow2->next);
1571          }
1572          not_ready = false;
1573       }
1574        
1575       /* set the dimensions of the row */ 
1576       tmprow->fill = Fill(tmprow, paperwidth);
1577       SetHeightOfRow(tmprow);
1578    } while (not_ready);
1579 }
1580
1581
1582 /* this is just a little changed version of break again */ 
1583 void LyXText::BreakAgainOneRow(Row * row)
1584 {
1585    /* get the next breakpoint */
1586    LyXParagraph::size_type z = NextBreakPoint(row, paperwidth);
1587    Row * tmprow = row;
1588    
1589    if (z < row->par->Last() ) {
1590       if (!row->next || (row->next && row->next->par != row->par)) {
1591          /* insert a new row */ 
1592          ++z;
1593          InsertRow(row, row->par, z);
1594          row = row->next;
1595          row->height = 0;
1596       }
1597       else  {
1598          row= row->next;
1599          ++z;
1600          if (row->pos != z)
1601             row->pos = z;
1602       }
1603    }
1604    else {
1605       /* if there are some rows too much, delete them */
1606       /* only if you broke the whole paragraph! */ 
1607       Row * tmprow2 = row;
1608       while (tmprow2->next && tmprow2->next->par == row->par) {
1609          tmprow2 = tmprow2->next;
1610       }
1611       while (tmprow2 != row) {
1612          tmprow2 = tmprow2->previous;
1613          RemoveRow(tmprow2->next);
1614       }
1615    }
1616    
1617    /* set the dimensions of the row */ 
1618    tmprow->fill = Fill(tmprow, paperwidth);
1619    SetHeightOfRow(tmprow);
1620 }
1621
1622
1623 void LyXText::BreakParagraph(char keep_layout)
1624 {
1625    LyXLayout const & layout = textclasslist.Style(parameters->textclass,
1626                                       cursor.par->GetLayout());
1627    
1628    /* table stuff -- begin */
1629    if (cursor.par->table) {
1630        // breaking of tables is only allowed at the beginning or the end */
1631        if (cursor.pos && cursor.pos < cursor.par->size() &&
1632            !cursor.par->table->ShouldBeVeryLastCell(NumberOfCell(cursor.par, cursor.pos)))
1633                return; // no breaking of tables allowed
1634    }
1635    /* table stuff -- end */
1636
1637    // this is only allowed, if the current paragraph is not empty or caption
1638    if ((cursor.par->Last() <= 0 && !cursor.par->IsDummy())
1639        && 
1640        layout.labeltype!= LABEL_SENSITIVE)
1641      return;
1642
1643    SetUndo(Undo::INSERT, 
1644            cursor.par->ParFromPos(cursor.pos)->previous, 
1645            cursor.par->ParFromPos(cursor.pos)->next); 
1646
1647    /* table stuff -- begin */
1648    if (cursor.par->table) {
1649        int cell = NumberOfCell(cursor.par, cursor.pos);
1650        if (cursor.par->table->ShouldBeVeryLastCell(cell))
1651            SetCursor(cursor.par, cursor.par->size());
1652    }
1653    /* table stuff -- end */
1654    
1655    // please break always behind a space
1656    if (cursor.pos < cursor.par->Last()
1657        && cursor.par->IsLineSeparator(cursor.pos))
1658      cursor.pos++;
1659    
1660    // break the paragraph
1661    if (keep_layout)
1662      keep_layout = 2;
1663    else 
1664      keep_layout = layout.isEnvironment();
1665    cursor.par->BreakParagraph(cursor.pos, keep_layout);
1666
1667    /* table stuff -- begin */
1668    if (cursor.par->table){
1669      // the table should stay with the contents
1670      if (!cursor.pos){
1671        cursor.par->Next()->table = cursor.par->table;
1672        cursor.par->table = 0;
1673      }
1674    }
1675    /* table stuff -- end */
1676
1677    // well this is the caption hack since one caption is really enough
1678    if (layout.labeltype == LABEL_SENSITIVE){
1679      if (!cursor.pos)
1680              cursor.par->SetLayout(0); // set to standard-layout
1681      else
1682              cursor.par->Next()->SetLayout(0); // set to standard-layout
1683    }
1684    
1685    /* if the cursor is at the beginning of a row without prior newline, 
1686     * move one row up! 
1687     * This touches only the screen-update. Otherwise we would may have
1688     * an empty row on the screen */
1689    if (cursor.pos && !cursor.row->par->IsNewline(cursor.row->pos -1) &&
1690        cursor.row->pos == cursor.pos) {
1691      CursorLeft();
1692    } 
1693    
1694    status = LyXText::NEED_MORE_REFRESH;
1695    refresh_row = cursor.row;
1696    refresh_y = cursor.y - cursor.row->baseline;
1697    
1698    // Do not forget the special right address boxes
1699    if (layout.margintype == MARGIN_RIGHT_ADDRESS_BOX) {
1700       while (refresh_row->previous &&
1701              refresh_row->previous->par == refresh_row->par) {
1702                 refresh_row = refresh_row->previous;
1703                 refresh_y -= refresh_row->height;
1704              }
1705    }
1706    RemoveParagraph(cursor.row);
1707    
1708    // set the dimensions of the cursor row
1709    cursor.row->fill = Fill(cursor.row, paperwidth);
1710
1711    SetHeightOfRow(cursor.row);
1712    
1713    while (!cursor.par->Next()->table && cursor.par->Next()->Last()
1714           && cursor.par->Next()->IsNewline(0))
1715      cursor.par->Next()->Erase(0);
1716    
1717    InsertParagraph(cursor.par->Next(), cursor.row);
1718
1719    UpdateCounters(cursor.row->previous);
1720    
1721    /* This check is necessary. Otherwise the new empty paragraph will
1722     * be deleted automatically. And it is more friendly for the user! */ 
1723    if (cursor.pos)
1724      SetCursor(cursor.par->Next(), 0);
1725    else
1726      SetCursor(cursor.par, 0);
1727    
1728    if (cursor.row->next)
1729      BreakAgain(cursor.row->next);
1730
1731    need_break_row = 0;
1732 }
1733
1734
1735 void LyXText::OpenFootnote()
1736 {
1737    LyXParagraph * endpar,* tmppar;
1738    Row * row;
1739    
1740    LyXParagraph * par = cursor.par->ParFromPos(cursor.pos);
1741    
1742    /* if there is no footnote in this paragraph, just return. */ 
1743    if (!par->next
1744        || par->next->footnoteflag != LyXParagraph::CLOSED_FOOTNOTE)
1745      return;
1746    
1747    /* ok, move the cursor right before the footnote */ 
1748    
1749    /* just a little faster than using CursorRight() */
1750    for (cursor.pos = 0;
1751         cursor.par->ParFromPos(cursor.pos) != par; cursor.pos++);
1752    /* now the cursor is at the beginning of the physical par */
1753    SetCursor(cursor.par,
1754              cursor.pos + cursor.par->ParFromPos(cursor.pos)->size());
1755    
1756    /* the cursor must be exactly before the footnote */ 
1757    par = cursor.par->ParFromPos(cursor.pos);
1758    
1759    status = LyXText::NEED_MORE_REFRESH;
1760    refresh_row = cursor.row;
1761    refresh_y = cursor.y - cursor.row->baseline;
1762    
1763    tmppar = cursor.par;
1764    endpar = cursor.par->Next();
1765    row = cursor.row;
1766    
1767    tmppar->OpenFootnote(cursor.pos);
1768    RemoveParagraph(row);
1769    /* set the dimensions of the cursor row */
1770    row->fill = Fill(row, paperwidth);
1771    SetHeightOfRow(row);
1772 #warning See comment on top of text.C
1773    tmppar = tmppar->Next();
1774    
1775    while (tmppar != endpar) {
1776       if (tmppar) {
1777          InsertParagraph(tmppar, row);
1778          while (row->next && row->next->par == tmppar)
1779            row = row->next;
1780          tmppar = tmppar->Next();
1781       }
1782    }
1783    SetCursor(par->next, 0);
1784    sel_cursor = cursor;
1785 }
1786    
1787
1788 /* table stuff -- begin*/
1789
1790 void LyXText::TableFeatures(int feature, string const & val) const
1791 {
1792         if (!cursor.par->table)
1793                 return; /* this should never happen */
1794   
1795         int actCell = NumberOfCell(cursor.par, cursor.pos);
1796         SetUndo(Undo::FINISH, 
1797                 cursor.par->ParFromPos(cursor.pos)->previous, 
1798                 cursor.par->ParFromPos(cursor.pos)->next); 
1799         
1800         switch (feature){
1801         case LyXTable::SET_PWIDTH:
1802                 cursor.par->table->SetPWidth(actCell, val);
1803                 break;
1804         case LyXTable::SET_SPECIAL_COLUMN:
1805         case LyXTable::SET_SPECIAL_MULTI:
1806                 cursor.par->table->SetAlignSpecial(actCell, val, feature);
1807                 break;
1808         default:
1809                 break;
1810         }
1811         RedoParagraph();
1812 }
1813
1814
1815 void LyXText::TableFeatures(int feature) const
1816 {
1817         int setLines = 0;
1818         int setAlign = LYX_ALIGN_LEFT;
1819         int lineSet;
1820         bool what;
1821     
1822     if (!cursor.par->table)
1823         return; /* this should never happen */
1824   
1825     int actCell = NumberOfCell(cursor.par, cursor.pos);
1826     SetUndo(Undo::FINISH, 
1827             cursor.par->ParFromPos(cursor.pos)->previous, 
1828             cursor.par->ParFromPos(cursor.pos)->next); 
1829
1830     switch (feature){
1831       case LyXTable::ALIGN_LEFT:
1832           setAlign= LYX_ALIGN_LEFT;
1833           break;
1834       case LyXTable::ALIGN_RIGHT:
1835           setAlign= LYX_ALIGN_RIGHT;
1836           break;
1837       case LyXTable::ALIGN_CENTER:
1838           setAlign= LYX_ALIGN_CENTER;
1839           break;
1840       default:
1841           break;
1842     }
1843     switch (feature){
1844       case LyXTable::APPEND_ROW: {
1845               LyXParagraph::size_type pos = cursor.pos;
1846
1847               /* move to the next row */
1848           int cell_org = actCell;
1849           int cell = cell_org;
1850
1851           // if there is a ContRow following this row I have to add
1852           // the row after the ContRow's
1853           if ((pos < cursor.par->Last()) &&
1854               cursor.par->table->RowHasContRow(cell_org)) {
1855               while((pos < cursor.par->Last()) &&
1856                     !cursor.par->table->IsContRow(cell)) {
1857                   while (pos < cursor.par->Last() &&
1858                          !cursor.par->IsNewline(pos))
1859                       ++pos;
1860                   if (pos < cursor.par->Last())
1861                       ++pos;
1862                   ++cell;
1863               }
1864               while((pos < cursor.par->Last()) &&
1865                     cursor.par->table->IsContRow(cell)) {
1866                   while (pos < cursor.par->Last() &&
1867                          !cursor.par->IsNewline(pos))
1868                       ++pos;
1869                   if (pos < cursor.par->Last())
1870                       ++pos;
1871                   ++cell;
1872               }
1873               cell_org = --cell;
1874               if (pos < cursor.par->Last())
1875                   --pos;
1876           }
1877           while (pos < cursor.par->Last() && 
1878                  (cell == cell_org || !cursor.par->table->IsFirstCell(cell))){
1879               while (pos < cursor.par->Last() && !cursor.par->IsNewline(pos))
1880                   ++pos;
1881               if (pos < cursor.par->Last())
1882                   ++pos;
1883               ++cell;
1884           }
1885                 
1886           /* insert the new cells */ 
1887           int number = cursor.par->table->NumberOfCellsInRow(cell_org);
1888           Language const * lang = cursor.par->getParLanguage();
1889           LyXFont font(LyXFont::ALL_INHERIT,lang);
1890           for (int i = 0; i < number; ++i) {
1891               cursor.par->InsertChar(pos, LyXParagraph::META_NEWLINE);
1892               cursor.par->SetFont(pos, font);
1893           }
1894                 
1895           /* append the row into the table */
1896           cursor.par->table->AppendRow(cell_org);
1897           RedoParagraph();
1898           return;
1899       }
1900       case LyXTable::APPEND_CONT_ROW: {
1901               LyXParagraph::size_type pos = cursor.pos;
1902           /* move to the next row */
1903           int cell_org = actCell;
1904           int cell = cell_org;
1905
1906           // if there is already a controw but not for this cell
1907           // the AppendContRow sets only the right values but does
1908           // not actually add a row
1909           if (cursor.par->table->RowHasContRow(cell_org) &&
1910               (cursor.par->table->CellHasContRow(cell_org)<0)) {
1911               cursor.par->table->AppendContRow(cell_org);
1912               RedoParagraph();
1913               return;
1914           }
1915           while (pos < cursor.par->Last() && 
1916                  (cell == cell_org
1917                   || !cursor.par->table->IsFirstCell(cell))){
1918               while (pos < cursor.par->Last() && !cursor.par->IsNewline(pos))
1919                   ++pos;
1920               if (pos < cursor.par->Last())
1921                   ++pos;
1922               ++cell;
1923           }
1924                 
1925           /* insert the new cells */ 
1926           int number = cursor.par->table->NumberOfCellsInRow(cell_org);
1927           Language const * lang = cursor.par->getParLanguage();
1928           LyXFont font(LyXFont::ALL_INHERIT,lang);
1929           for (int i = 0; i < number; ++i) {
1930               cursor.par->InsertChar(pos, LyXParagraph::META_NEWLINE);
1931               cursor.par->SetFont(pos, font);
1932           }
1933
1934           /* append the row into the table */
1935           cursor.par->table->AppendContRow(cell_org);
1936           RedoParagraph();
1937           return;
1938       }
1939       case LyXTable::APPEND_COLUMN: {
1940               LyXParagraph::size_type pos = 0;
1941           int cell_org = actCell;
1942           int cell = 0;
1943           Language const * lang = cursor.par->getParLanguage();
1944           LyXFont font(LyXFont::ALL_INHERIT,lang);
1945           do{
1946               if (pos && (cursor.par->IsNewline(pos-1))){
1947                   if (cursor.par->table->AppendCellAfterCell(cell_org, cell)) {
1948                       cursor.par->InsertChar(pos, LyXParagraph::META_NEWLINE);
1949                       cursor.par->SetFont(pos, font);
1950                       if (pos <= cursor.pos)
1951                           cursor.pos++;
1952                       ++pos;
1953                   }
1954                   ++cell;
1955               }
1956               ++pos;
1957           } while (pos <= cursor.par->Last());
1958           /* remember that the very last cell doesn't end with a newline.
1959              This saves one byte memory per table ;-) */
1960           if (cursor.par->table->AppendCellAfterCell(cell_org, cell)) {
1961                   LyXParagraph::size_type last = cursor.par->Last();
1962                   cursor.par->InsertChar(last, LyXParagraph::META_NEWLINE);
1963                   cursor.par->SetFont(last, font);
1964           }
1965                 
1966           /* append the column into the table */ 
1967           cursor.par->table->AppendColumn(cell_org);
1968                 
1969           RedoParagraph();
1970           return;
1971       }
1972       case LyXTable::DELETE_ROW:
1973           if (owner_->the_locking_inset)
1974               owner_->unlockInset(owner_->the_locking_inset);
1975           RemoveTableRow(&cursor);
1976           RedoParagraph();
1977           return;
1978         
1979       case LyXTable::DELETE_COLUMN: {
1980               LyXParagraph::size_type pos = 0;
1981           int cell_org = actCell;
1982           int cell = 0;
1983           if (owner_->the_locking_inset)
1984               owner_->unlockInset(owner_->the_locking_inset);
1985           do {
1986               if (!pos || (cursor.par->IsNewline(pos-1))){
1987                   if (cursor.par->table->DeleteCellIfColumnIsDeleted(cell, cell_org)){
1988                       // delete one cell
1989                       while (pos < cursor.par->Last() && !cursor.par->IsNewline(pos))
1990                           cursor.par->Erase(pos);
1991                       if (pos < cursor.par->Last())
1992                           cursor.par->Erase(pos);
1993                       else 
1994                           cursor.par->Erase(pos - 1); // the missing newline at the end of a table
1995                       --pos; // because of pos++ below
1996                   }   
1997                   ++cell;
1998               }
1999               ++pos;
2000           } while (pos <= cursor.par->Last());
2001                 
2002           /* delete the column from the table */ 
2003           cursor.par->table->DeleteColumn(cell_org);
2004                 
2005           /* set the cursor to the beginning of the table, where else? */ 
2006           cursor.pos = 0;
2007           RedoParagraph();
2008           return;
2009       }
2010       case LyXTable::TOGGLE_LINE_TOP:
2011           lineSet = !cursor.par->table->TopLine(actCell);
2012           if (!selection){
2013               cursor.par->table->SetTopLine(actCell, lineSet);
2014           } else {
2015                   LyXParagraph::size_type i;
2016                   int n = -1, m = -2;
2017               for (i = sel_start_cursor.pos; i <= sel_end_cursor.pos; ++i){
2018                   if ((n = NumberOfCell(sel_start_cursor.par, i)) != m) {
2019                       cursor.par->table->SetTopLine(n, lineSet);
2020                       m = n;
2021                   }
2022               }
2023           }
2024           RedoParagraph();
2025           return;
2026     
2027       case LyXTable::TOGGLE_LINE_BOTTOM:
2028           lineSet = !cursor.par->table->BottomLine(actCell);
2029           if (!selection){
2030               cursor.par->table->SetBottomLine(actCell, lineSet);
2031           } else {
2032                   LyXParagraph::size_type i;
2033                   int n = -1, m = -2;
2034               for (i = sel_start_cursor.pos; i <= sel_end_cursor.pos; ++i) {
2035                   if ((n = NumberOfCell(sel_start_cursor.par, i)) != m) {
2036                       cursor.par->table->SetBottomLine(n, lineSet);
2037                       m = n;
2038                   }
2039               }
2040           }
2041           RedoParagraph();
2042           return;
2043                 
2044       case LyXTable::TOGGLE_LINE_LEFT:
2045           lineSet = !cursor.par->table->LeftLine(actCell);
2046           if (!selection){
2047               cursor.par->table->SetLeftLine(actCell, lineSet);
2048           } else {
2049                   LyXParagraph::size_type i;
2050                   int n = -1, m = -2;
2051               for (i = sel_start_cursor.pos; i <= sel_end_cursor.pos; ++i){
2052                   if ((n= NumberOfCell(sel_start_cursor.par, i)) != m) {
2053                       cursor.par->table->SetLeftLine(n, lineSet);
2054                       m = n;
2055                   }
2056               }
2057           }
2058           RedoParagraph();
2059           return;
2060
2061       case LyXTable::TOGGLE_LINE_RIGHT:
2062           lineSet = !cursor.par->table->RightLine(actCell);
2063           if (!selection){
2064               cursor.par->table->SetRightLine(actCell, lineSet);
2065           } else {
2066                   int n = -1, m = -2;
2067                   LyXParagraph::size_type i = sel_start_cursor.pos;
2068               for (; i <= sel_end_cursor.pos; ++i) {
2069                   if ((n= NumberOfCell(sel_start_cursor.par, i)) != m) {
2070                       cursor.par->table->SetRightLine(n, lineSet);
2071                       m = n;
2072                   }
2073               }
2074           }
2075           RedoParagraph();
2076           return;
2077     
2078       case LyXTable::ALIGN_LEFT:
2079       case LyXTable::ALIGN_RIGHT:
2080       case LyXTable::ALIGN_CENTER:
2081           if (!selection){
2082               cursor.par->table->SetAlignment(actCell, setAlign);
2083           } else {
2084               int n = -1, m = -2;
2085               LyXParagraph::size_type i = sel_start_cursor.pos;
2086               for (; i <= sel_end_cursor.pos; ++i) {
2087                   if ((n= NumberOfCell(sel_start_cursor.par, i)) != m) {
2088                       cursor.par->table->SetAlignment(n, setAlign);
2089                       m = n;
2090                   }
2091               }
2092           }
2093           RedoParagraph();
2094           return;
2095                 
2096       case LyXTable::DELETE_TABLE:
2097           SetCursorIntern(cursor.par, 0);
2098           delete cursor.par->table;
2099           cursor.par->table = 0;
2100           // temporary: Should put table in simple_cut_buffer (with before and after
2101           // dummy-paragraph !! 
2102           // not necessar anymore with UNDO :)
2103           for (LyXParagraph::size_type i = 
2104                        cursor.par->size() - 1; i >= 0; --i)
2105               cursor.par->Erase(i);
2106           RedoParagraph();
2107           return;
2108                 
2109       case LyXTable::MULTICOLUMN: {
2110           int number = 0;
2111           // check wether we are completly in a multicol
2112           int multicol = cursor.par->table->IsMultiColumn(actCell);
2113           if (multicol && selection && sel_start_cursor.row == sel_end_cursor.row){
2114               multicol = NumberOfCell(sel_start_cursor.par, sel_start_cursor.pos)
2115                   == NumberOfCell(sel_end_cursor.par, sel_end_cursor.pos);
2116           }
2117
2118           if (multicol){
2119               int newlines = cursor.par->table->UnsetMultiColumn(actCell);
2120               LyXParagraph::size_type pos = cursor.pos;
2121               while (pos < cursor.par->Last() && !cursor.par->IsNewline(pos))
2122                   ++pos;
2123               for (; newlines; --newlines)
2124                   cursor.par->InsertChar(pos, LyXParagraph::META_NEWLINE);
2125               RedoParagraph();
2126               return;
2127           }
2128           else {
2129               // selection must be in one row (or no selection)
2130               if (!selection){
2131                   cursor.par->table->SetMultiColumn(NumberOfCell(cursor.par,
2132                                                                  cursor.pos),
2133                                                     1);
2134                   RedoParagraph();
2135                   return;
2136               }
2137               else {
2138                   if (sel_start_cursor.row == sel_end_cursor.row){
2139                       LyXParagraph::size_type i;
2140                       number = 1;
2141                       for (i = sel_start_cursor.pos;
2142                            i < sel_end_cursor.pos; ++i){
2143                           if (sel_start_cursor.par->IsNewline(i)){
2144                               sel_start_cursor.par->Erase(i);
2145                               // check for double-blanks
2146                               if ((i && !sel_start_cursor.par->IsLineSeparator(i-1))
2147                                   &&
2148                                   (i < sel_start_cursor.par->Last() 
2149                                    && !sel_start_cursor.par->IsLineSeparator(i)))
2150                                   sel_start_cursor.par->InsertChar(i, ' ');
2151                               else {
2152                                   sel_end_cursor.pos--;
2153                                   --i;
2154                               }
2155                               ++number;
2156                           }
2157                       }
2158                       cursor.par->table->
2159                           SetMultiColumn(NumberOfCell(sel_start_cursor.par,
2160                                                       sel_start_cursor.pos),
2161                                          number);
2162                       cursor.pos = sel_start_cursor.pos;
2163                       RedoParagraph();
2164                       return;
2165                   }
2166                   else {
2167                       WriteAlert(_("Impossible Operation!"), 
2168                                  _("Multicolumns can only be horizontally."), 
2169                                  _("Sorry."));
2170                   }
2171               }
2172           }
2173           break;
2174       }
2175       case LyXTable::SET_ALL_LINES:
2176           setLines = 1;
2177       case LyXTable::UNSET_ALL_LINES:
2178           if (!selection){
2179               cursor.par->table->SetAllLines(NumberOfCell(cursor.par,
2180                                                           cursor.pos),
2181                                              setLines);
2182           } else {
2183                   LyXParagraph::size_type i;
2184                   int n = -1, m = -2;
2185               for (i = sel_start_cursor.pos; i <= sel_end_cursor.pos; ++i) {
2186                   if ((n= NumberOfCell(sel_start_cursor.par, i)) != m) {
2187                       cursor.par->table->SetAllLines(n, setLines);
2188                       m = n;
2189                   }
2190               }
2191           }
2192           RedoParagraph();
2193           return;
2194       case LyXTable::SET_LONGTABLE:
2195           cursor.par->table->SetLongTable(true);
2196           return;
2197       case LyXTable::UNSET_LONGTABLE:
2198           cursor.par->table->SetLongTable(false);
2199           return;
2200       case LyXTable::SET_ROTATE_TABLE:
2201           cursor.par->table->SetRotateTable(true);
2202           return;
2203       case LyXTable::UNSET_ROTATE_TABLE:
2204           cursor.par->table->SetRotateTable(false);
2205           return;
2206       case LyXTable::SET_ROTATE_CELL:
2207           if (!selection){
2208               cursor.par->table->SetRotateCell(actCell, true);
2209           } else {
2210                   LyXParagraph::size_type i;
2211                   int n = -1, m = -2;
2212               for (i = sel_start_cursor.pos; i <= sel_end_cursor.pos; ++i){
2213                   if ((n = NumberOfCell(sel_start_cursor.par, i)) != m) {
2214                       cursor.par->table->SetRotateCell(n, true);
2215                       m = n;
2216                   }
2217               }
2218           }
2219           return;
2220       case LyXTable::UNSET_ROTATE_CELL:
2221           if (!selection){
2222               cursor.par->table->SetRotateCell(actCell, false);
2223           } else {
2224                   int n = -1, m = -2;
2225                   LyXParagraph::size_type i = sel_start_cursor.pos;
2226               for (; i <= sel_end_cursor.pos; ++i) {
2227                   if ((n= NumberOfCell(sel_start_cursor.par, i)) != m) {
2228                       cursor.par->table->SetRotateCell(n, false);
2229                       m = n;
2230                   }
2231               }
2232           }
2233           return;
2234       case LyXTable::SET_LINEBREAKS:
2235           what = !cursor.par->table->Linebreaks(cursor.par->table->FirstVirtualCell(actCell));
2236           if (!selection){
2237               cursor.par->table->SetLinebreaks(actCell, what);
2238           } else {
2239                   LyXParagraph::size_type i;
2240                   int n = -1, m = -2;
2241               for (i = sel_start_cursor.pos; i <= sel_end_cursor.pos; ++i) {
2242                   if ((n = NumberOfCell(sel_start_cursor.par, i)) != m) {
2243                       cursor.par->table->SetLinebreaks(n, what);
2244                       m = n;
2245                   }
2246               }
2247           }
2248           return;
2249       case LyXTable::SET_LTFIRSTHEAD:
2250           cursor.par->table->SetLTHead(actCell, true);
2251           return;
2252       case LyXTable::SET_LTHEAD:
2253           cursor.par->table->SetLTHead(actCell, false);
2254           return;
2255       case LyXTable::SET_LTFOOT:
2256           cursor.par->table->SetLTFoot(actCell, false);
2257           return;
2258       case LyXTable::SET_LTLASTFOOT:
2259           cursor.par->table->SetLTFoot(actCell, true);
2260           return;
2261       case LyXTable::SET_LTNEWPAGE:
2262           what = !cursor.par->table->LTNewPage(actCell);
2263           cursor.par->table->SetLTNewPage(actCell, what);
2264           return;
2265     }
2266 }
2267         
2268
2269 void LyXText::InsertCharInTable(char c)
2270 {
2271         Row * row;
2272         Row * tmprow;
2273         long y;
2274         bool jumped_over_space;
2275         
2276         /* first check, if there will be two blanks together or a blank at 
2277          * the beginning of a paragraph. 
2278          * I decided to handle blanks like normal characters, the main 
2279          * difference are the special checks when calculating the row.fill
2280          * (blank does not count at the end of a row) and the check here */ 
2281         
2282         LyXFont realtmpfont = real_current_font;
2283         LyXFont rawtmpfont = current_font; /* store the current font.
2284                                             * This is because of the use
2285                                             * of cursor movements. The moving
2286                                             * cursor would refresh the 
2287                                             * current font */
2288
2289         // Get the font that is used to calculate the baselineskip
2290         LyXParagraph::size_type const lastpos = 
2291                 cursor.par->Last();
2292         LyXFont rawparfont = cursor.par->GetFontSettings(lastpos - 1);
2293
2294         jumped_over_space = false;
2295         if (IsLineSeparatorChar(c)) {
2296
2297 #ifndef FIX_DOUBLE_SPACE
2298                 /* avoid double blanks but insert the new blank because
2299                  * of a possible font change */
2300                 if (cursor.pos < lastpos &&
2301                     cursor.par->IsLineSeparator(cursor.pos)) {
2302                         cursor.par->Erase(cursor.pos);
2303                         jumped_over_space = true;
2304                 } else
2305 #endif
2306                         if ((cursor.pos > 0 && 
2307                           cursor.par->IsLineSeparator(cursor.pos - 1))
2308                          || (cursor.pos > 0 && cursor.par->IsNewline(cursor.pos - 1))
2309                           || (cursor.pos == 0 &&
2310                               !(cursor.par->Previous()
2311                               && cursor.par->Previous()->footnoteflag
2312                               == LyXParagraph::OPEN_FOOTNOTE)))
2313                         return;
2314         } else if (IsNewlineChar(c)) {
2315             if (!IsEmptyTableCell()) {
2316                 TableFeatures(LyXTable::APPEND_CONT_ROW);
2317                 CursorDown();
2318             }
2319           return;
2320         }
2321    
2322         row = cursor.row;
2323         y = cursor.y - row->baseline;
2324         if (c != LyXParagraph::META_INSET)      /* in this case LyXText::InsertInset 
2325                                          * already inserted the character */
2326                 cursor.par->InsertChar(cursor.pos, c);
2327         SetCharFont(cursor.par, cursor.pos, rawtmpfont);
2328
2329         if (!jumped_over_space) {
2330                 /* refresh the positions */
2331                 tmprow = row;
2332                 while (tmprow->next && tmprow->next->par == row->par) {
2333                         tmprow = tmprow->next;
2334                         tmprow->pos++;
2335                 }
2336         }
2337
2338         cursor.pos++;
2339
2340         CheckParagraphInTable(cursor.par, cursor.pos);
2341         
2342         current_font = rawtmpfont;
2343         real_current_font = realtmpfont;
2344         
2345         /* check, whether the last character's font has changed. */
2346         if (cursor.pos && cursor.pos == cursor.par->Last()
2347             && rawparfont != rawtmpfont)
2348                 RedoHeightOfParagraph(cursor);
2349 }
2350
2351
2352 void LyXText::CheckParagraphInTable(LyXParagraph * par,
2353                                     LyXParagraph::size_type pos)
2354 {
2355         
2356         if (par->GetChar(pos) == LyXParagraph::META_INSET &&
2357             par->GetInset(pos) && par->GetInset(pos)->display()){
2358           par->GetInset(pos)->display(false);
2359         }
2360
2361         long y;
2362         Row * row = GetRow(par, pos, y);
2363         
2364         int tmpheight = row->height;
2365         SetHeightOfRow(row);
2366
2367         LyXParagraph::size_type tmp_pos = pos;
2368         /* update the table information */
2369         while (tmp_pos && !par->IsNewline(tmp_pos - 1))
2370                 --tmp_pos;
2371         if (par->table->SetWidthOfCell(NumberOfCell(par, pos),
2372                                        WidthOfCell(par, tmp_pos))) {
2373                 LyXCursor tmpcursor = cursor;
2374                 SetCursorIntern(par, pos);
2375                 /* make a complete redraw */
2376                 RedoDrawingOfParagraph(cursor);
2377                 cursor = tmpcursor;
2378         }
2379         else {
2380                 /* redraw only the row */
2381                 LyXCursor tmpcursor = cursor;
2382                 SetCursorIntern(par, pos);
2383 #warning See comment on top of text.C
2384                 refresh_y = y;
2385                 refresh_x = cursor.x;
2386                 refresh_row = row;
2387                 refresh_pos = cursor.pos;
2388                 cursor = tmpcursor;
2389                 
2390                 if (tmpheight == row->height)
2391                         status = LyXText::NEED_VERY_LITTLE_REFRESH;
2392                 else
2393                         status = LyXText::NEED_MORE_REFRESH;
2394         }
2395         SetCursorIntern(cursor.par, cursor.pos);
2396 }
2397
2398
2399 void LyXText::BackspaceInTable()
2400 {
2401         Row * tmprow, * row;
2402         long y;
2403         
2404         LyXFont rawtmpfont = current_font;
2405         LyXFont realtmpfont = real_current_font;
2406
2407         // Get the font that is used to calculate the baselineskip
2408         int const lastpos = cursor.par->Last();
2409         LyXFont rawparfont = cursor.par->GetFontSettings(lastpos - 1);
2410         
2411         if (cursor.pos == 0) {
2412                 /* no pasting of table paragraphs */
2413                 
2414                 CursorLeft();
2415         } else {
2416                 /* this is the code for a normal backspace, not pasting
2417                  * any paragraphs */ 
2418                 SetUndo(Undo::DELETE, 
2419                         cursor.par->ParFromPos(cursor.pos)->previous, 
2420                         cursor.par->ParFromPos(cursor.pos)->next); 
2421           
2422                 CursorLeftIntern();
2423                 
2424                 /* some insets are undeletable here */
2425                 if (cursor.par->GetChar(cursor.pos) == LyXParagraph::META_INSET) {
2426                         if (!cursor.par->GetInset(cursor.pos)->Deletable())
2427                                 return;
2428                 }
2429                 
2430                 row = cursor.row;
2431                 y = cursor.y - row->baseline;
2432                 
2433                 /* some special code when deleting a newline. */
2434                 if (cursor.par->IsNewline(cursor.pos)) {
2435                         /* nothing :-) */
2436                         return;
2437                 }
2438                 else {
2439                         cursor.par->Erase(cursor.pos);
2440                         
2441                         /* refresh the positions */
2442                         tmprow = row;
2443                         while (tmprow->next && tmprow->next->par == row->par) {
2444                                 tmprow = tmprow->next;
2445                                 tmprow->pos--;
2446                         }
2447
2448 #ifndef FIX_DOUBLE_SPACE
2449                         /* delete superfluous blanks */ 
2450                         if (cursor.pos < cursor.par->Last() - 1 &&
2451                         (cursor.par->IsLineSeparator(cursor.pos))) {
2452                                 
2453                                 if (cursor.pos == BeginningOfMainBody(cursor.par)
2454                                 || !cursor.pos 
2455                                 || cursor.par->IsLineSeparator(cursor.pos - 1)) {
2456                                         cursor.par->Erase(cursor.pos);
2457                                         /* refresh the positions */
2458                                         tmprow = row;
2459                                         while (tmprow->next && 
2460                                                tmprow->next->par == row->par) {
2461                                                 tmprow = tmprow->next;
2462                                                 tmprow->pos--;
2463                                         }
2464                                         if (cursor.pos)   /* move one character left */
2465                                                 cursor.pos--;
2466                                 }
2467                         }
2468 #endif
2469                 }
2470       
2471                 CheckParagraphInTable(cursor.par, cursor.pos);
2472       
2473                 /* check, wether the last characters font has changed. */ 
2474                 if (cursor.pos && cursor.pos == cursor.par->Last()
2475                     && rawparfont != rawtmpfont)
2476                         RedoHeightOfParagraph(cursor);
2477
2478                 /* restore the current font 
2479                  * That is what a user expects! */
2480                 current_font = rawtmpfont;
2481                 real_current_font = realtmpfont;
2482         }
2483         SetCursorIntern(cursor.par, cursor.pos);
2484 }
2485
2486 /* table stuff -- end*/
2487
2488
2489 /* just a macro to make some thing easier. */ 
2490 void LyXText::RedoParagraph() const
2491 {
2492 #if 1
2493         // I suspect this version will work
2494         // also.
2495         ClearSelection();
2496         RedoParagraphs(cursor, cursor.par->Next());
2497         SetCursorIntern(cursor.par, cursor.pos);
2498 #else
2499         LyXCursor tmpcursor = cursor;
2500         ClearSelection();
2501         RedoParagraphs(cursor, cursor.par->Next());
2502         SetCursorIntern(tmpcursor.par, tmpcursor.pos);
2503 #endif
2504 }
2505
2506
2507 /* insert a character, moves all the following breaks in the 
2508  * same Paragraph one to the right and make a rebreak */
2509 void LyXText::InsertChar(char c)
2510 {
2511         SetUndo(Undo::INSERT, 
2512                 cursor.par->ParFromPos(cursor.pos)->previous, 
2513                 cursor.par->ParFromPos(cursor.pos)->next);
2514
2515         /* When the free-spacing option is set for the current layout,
2516          * disable the double-space checking */
2517
2518         bool freeSpacing = 
2519                 textclasslist.Style(parameters->textclass,
2520                                cursor.row->par->GetLayout()).free_spacing;
2521
2522         /* table stuff -- begin*/
2523         if (cursor.par->table) {
2524                 InsertCharInTable(c);
2525                 charInserted();
2526                 return;
2527         }
2528         /* table stuff -- end*/
2529    
2530         /* First check, if there will be two blanks together or a blank at 
2531           the beginning of a paragraph. 
2532           I decided to handle blanks like normal characters, the main 
2533           difference are the special checks when calculating the row.fill
2534           (blank does not count at the end of a row) and the check here */ 
2535
2536         // The bug is triggered when we type in a description environment:
2537         // The current_font is not changed when we go from label to main text
2538         // and it should (along with realtmpfont) when we type the space.
2539 #ifdef WITH_WARNINGS
2540 #warning There is a bug here! (Asger)
2541 #endif
2542         
2543         LyXFont realtmpfont = real_current_font;
2544         LyXFont rawtmpfont = current_font;  /* store the current font.
2545                                      * This is because of the use
2546                                      * of cursor movements. The moving
2547                                      * cursor would refresh the 
2548                                      * current font */
2549
2550         // Get the font that is used to calculate the baselineskip
2551         LyXParagraph::size_type lastpos = cursor.par->Last();
2552         LyXFont rawparfont = cursor.par->GetFontSettings(lastpos - 1);
2553
2554         bool jumped_over_space = false;
2555    
2556         if (!freeSpacing && IsLineSeparatorChar(c)) {
2557 #ifndef FIX_DOUBLE_SPACE
2558                 if (cursor.pos < lastpos
2559                     && cursor.par->IsLineSeparator(cursor.pos)) {
2560                         /* the user inserted a space before a space. So we
2561                          * will just make a CursorRight. BUT: The font of this
2562                          * space should be set to current font. That is why
2563                          * we need to rebreak perhaps. If there is a protected
2564                          * blank at the end of a row we have to force
2565                          * a rebreak.*/ 
2566            
2567                         owner_->owner()->getMiniBuffer()
2568                                 ->Set(_("You cannot type two spaces this way. "
2569                                         " Please read the Tutorial."));
2570 #if 1
2571                         // How can this ever happen?
2572                         if (cursor.pos == RowLast(cursor.row)
2573                             && !IsLineSeparatorChar(c))
2574                                 cursor.row->fill = -1;  // force rebreak
2575                         cursor.par->Erase(cursor.pos);
2576                         jumped_over_space = true;
2577 #else
2578                         // Seems to me that this works just as well.
2579                         CursorRight();
2580                         charInserted();
2581                         return;
2582 #endif
2583                 } else
2584 #endif   
2585                 if ((cursor.pos > 0 
2586                      && cursor.par->IsLineSeparator(cursor.pos - 1))
2587                     || (cursor.pos > 0
2588                         && cursor.par->IsNewline(cursor.pos - 1))
2589                     || (cursor.pos == 0
2590                         && !(cursor.par->Previous()
2591                              && cursor.par->Previous()->footnoteflag
2592                              == LyXParagraph::OPEN_FOOTNOTE))) {
2593                         if (cursor.pos == 0 )
2594                                 owner_->owner()->getMiniBuffer()->Set(_("You cannot insert a space at the beginning of a paragraph.  Please read the Tutorial."));
2595                         else
2596                                 owner_->owner()->getMiniBuffer()->Set(_("You cannot type two spaces this way.  Please read the Tutorial."));
2597                         charInserted();
2598                         return;
2599                 }
2600         } else if (IsNewlineChar(c)) {
2601                 if (cursor.par->FirstPhysicalPar() == cursor.par
2602                     && cursor.pos <= BeginningOfMainBody(cursor.par)) {
2603                         charInserted();
2604                         return;
2605                 }
2606                 /* No newline at first position 
2607                  * of a paragraph or behind labels. 
2608                  * TeX does not allow that. */
2609                 
2610                 if (cursor.pos < cursor.par->Last() &&
2611                     cursor.par->IsLineSeparator(cursor.pos))
2612                         CursorRightIntern(); // newline always after a blank!
2613                 cursor.row->fill = -1;         // to force a new break
2614         }
2615    
2616         // the display inset stuff
2617         if (cursor.row->par->GetChar(cursor.row->pos) == LyXParagraph::META_INSET
2618             && cursor.row->par->GetInset(cursor.row->pos)
2619             && cursor.row->par->GetInset(cursor.row->pos)->display())
2620                 cursor.row->fill = -1; // to force a new break  
2621
2622         // get the cursor row fist
2623         Row * row = cursor.row;
2624         long y = cursor.y - row->baseline;
2625         if (c != LyXParagraph::META_INSET) /* Here case LyXText::InsertInset 
2626                                             * already insertet the character */
2627                 cursor.par->InsertChar(cursor.pos, c);
2628         SetCharFont(cursor.par, cursor.pos, rawtmpfont);
2629
2630         if (!jumped_over_space) {
2631                 // refresh the positions
2632                 Row * tmprow = row;
2633                 while (tmprow->next && tmprow->next->par == row->par) {
2634                         tmprow = tmprow->next;
2635                         tmprow->pos++;
2636                 }
2637         }
2638    
2639         // Is there a break one row above
2640         if ((cursor.par->IsLineSeparator(cursor.pos)
2641              || cursor.par->IsNewline(cursor.pos)
2642              || cursor.row->fill == -1)
2643             && row->previous && row->previous->par == row->par) {
2644                 LyXParagraph::size_type z = NextBreakPoint(row->previous,
2645                                                            paperwidth);
2646                 if ( z >= row->pos) {
2647                         row->pos = z + 1;
2648                         
2649                         // set the dimensions of the row above
2650                         row->previous->fill = Fill(row->previous, paperwidth);
2651
2652                         SetHeightOfRow(row->previous);
2653              
2654                         y -= row->previous->height;
2655                         refresh_y = y;
2656                         refresh_row = row->previous;
2657                         status = LyXText::NEED_MORE_REFRESH;
2658              
2659                         BreakAgainOneRow(row);
2660
2661                         current_font = rawtmpfont;
2662                         real_current_font = realtmpfont;
2663                         SetCursor(cursor.par, cursor.pos + 1, false);
2664                         /* cursor MUST be in row now */
2665              
2666                         if (row->next && row->next->par == row->par)
2667                                 need_break_row = row->next;
2668                         else
2669                                 need_break_row = 0;
2670              
2671                         // check, wether the last characters font has changed. 
2672                         if (cursor.pos && cursor.pos == cursor.par->Last()
2673                             && rawparfont != rawtmpfont)
2674                                 RedoHeightOfParagraph(cursor);
2675                         
2676                         charInserted();
2677                         return;
2678                 }
2679         }
2680    
2681         /* recalculate the fill of the row */ 
2682         if (row->fill >= 0)  /* needed because a newline
2683                               * will set fill to -1. Otherwise
2684                               * we would not get a rebreak! */
2685                 row->fill = Fill(row, paperwidth);
2686         if (row->fill < 0 ) {
2687                 refresh_y = y;
2688                 refresh_row = row; 
2689                 refresh_x = cursor.x;
2690                 refresh_pos = cursor.pos;
2691                 status = LyXText::NEED_MORE_REFRESH;
2692                 BreakAgainOneRow(row); 
2693                 /* will the cursor be in another row now? */ 
2694                 if (RowLast(row) <= cursor.pos + 1 && row->next) {
2695                         if (row->next && row->next->par == row->par)
2696                                 /* this should
2697                                  * always be true */
2698                                 row = row->next;
2699                         BreakAgainOneRow(row);
2700                 }
2701                 current_font = rawtmpfont;
2702                 real_current_font = realtmpfont;
2703                 SetCursor(cursor.par, cursor.pos + 1, false);
2704                 if (row->next && row->next->par == row->par)
2705                         need_break_row = row->next;
2706                 else
2707                         need_break_row = 0;             
2708         } else {
2709                 refresh_y = y;
2710                 refresh_x = cursor.x;
2711                 refresh_row = row;
2712                 refresh_pos = cursor.pos;
2713                 
2714                 int tmpheight = row->height;
2715                 SetHeightOfRow(row);
2716                 if (tmpheight == row->height)
2717                         status = LyXText::NEED_VERY_LITTLE_REFRESH;
2718                 else
2719                         status = LyXText::NEED_MORE_REFRESH;
2720             
2721                 current_font = rawtmpfont;
2722                 real_current_font = realtmpfont;
2723                 SetCursor(cursor.par, cursor.pos + 1, false);
2724         }
2725
2726         /* check, wether the last characters font has changed. */ 
2727         if (cursor.pos && cursor.pos == cursor.par->Last()
2728             && rawparfont != rawtmpfont) {
2729                 RedoHeightOfParagraph(cursor);
2730         } else {
2731                 /* now the special right address boxes */
2732                 if (textclasslist.Style(parameters->textclass,
2733                                    cursor.par->GetLayout()).margintype
2734                     == MARGIN_RIGHT_ADDRESS_BOX) {
2735                         RedoDrawingOfParagraph(cursor); 
2736                 }
2737         }
2738
2739         charInserted();
2740 }
2741    
2742
2743 void LyXText::charInserted()
2744 {
2745         // Here we could call FinishUndo for every 20 characters inserted.
2746         // This is from my experience how emacs does it.
2747         static unsigned int counter = 0;
2748         if (counter < 20) {
2749                 ++counter;
2750         } else {
2751                 FinishUndo();
2752                 counter = 0;
2753         }
2754 }
2755
2756 void LyXText::PrepareToPrint(Row * row, float & x,
2757                              float & fill_separator, 
2758                              float & fill_hfill,
2759                              float & fill_label_hfill,
2760                              bool bidi) const
2761 {
2762         float nh, nlh, ns;
2763         
2764         float w = row->fill;
2765         fill_hfill = 0;
2766         fill_label_hfill = 0;
2767         fill_separator = 0;
2768         fill_label_hfill = 0;
2769
2770         LyXDirection direction = row->par->getParDirection();
2771
2772         if (direction == LYX_DIR_RIGHT_TO_LEFT) {
2773                 x = RightMargin(row);
2774                 if (row->par->footnoteflag == LyXParagraph::OPEN_FOOTNOTE) {
2775                         LyXFont font(LyXFont::ALL_SANE);
2776                         font.setSize(LyXFont::SIZE_SMALL);
2777                         x += font.textWidth("Mwide-figM", 10);
2778                 }
2779         }
2780         else
2781                 x = LeftMargin(row);
2782         
2783         /* is there a manual margin with a manual label */ 
2784         if (textclasslist.Style(parameters->textclass,
2785                            row->par->GetLayout()).margintype == MARGIN_MANUAL
2786             && textclasslist.Style(parameters->textclass,
2787                               row->par->GetLayout()).labeltype == LABEL_MANUAL) {
2788                
2789                 nlh = NumberOfLabelHfills(row) + 1; /* one more since labels 
2790                                                     * are left aligned*/ 
2791                 if (nlh && !row->par->GetLabelWidthString().empty()) {
2792                         fill_label_hfill = LabelFill(row) / nlh;
2793                 }
2794         }
2795                 
2796         /* are there any hfills in the row? */ 
2797         nh = NumberOfHfills(row);
2798         
2799 /* table stuff -- begin*/
2800         if (row->par->table) {
2801            w = paperwidth - row->par->table->WidthOfTable()
2802            - x - RightMargin(row);
2803            nh = 0; /* ignore hfills in tables */ 
2804         }
2805 /* table stuff -- end*/
2806
2807         if (nh)
2808           fill_hfill = w /nh;
2809         else  {
2810            /* is it block, flushleft or flushright? 
2811             * set x how you need it */
2812         int align;
2813         if (row->par->FirstPhysicalPar()->align == LYX_ALIGN_LAYOUT)
2814           align = textclasslist.Style(parameters->textclass, row->par->GetLayout()).align;
2815         else
2816           align = row->par->FirstPhysicalPar()->align;
2817            
2818            /* center displayed insets */ 
2819            if (row->par->GetChar(row->pos) == LyXParagraph::META_INSET
2820                && row->par->GetInset(row->pos)
2821                && row->par->GetInset(row->pos)->display())
2822              align = LYX_ALIGN_CENTER;
2823
2824            switch (align) {
2825             case LYX_ALIGN_BLOCK:
2826               ns = NumberOfSeparators(row);
2827               if (ns && row->next && row->next->par == row->par &&
2828                   !(row->next->par->IsNewline(row->next->pos-1))
2829                   && !(row->next->par->GetChar(row->next->pos) == LyXParagraph::META_INSET
2830                        && row->next->par->GetInset(row->next->pos)
2831                        && row->next->par->GetInset(row->next->pos)->display())
2832                   )
2833                 fill_separator = w / ns;
2834               else if (direction == LYX_DIR_RIGHT_TO_LEFT)
2835                 x += w;
2836               break;
2837             case LYX_ALIGN_RIGHT:
2838               x += w;
2839               break;
2840             case LYX_ALIGN_CENTER:
2841               x += w / 2;
2842               break;
2843            }
2844         }
2845         if (!bidi)
2846                 return;
2847
2848         ComputeBidiTables(row);
2849         if (direction == LYX_DIR_RIGHT_TO_LEFT) {
2850                 LyXParagraph::size_type main_body = 
2851                         BeginningOfMainBody(row->par);
2852                 LyXParagraph::size_type last = RowLast(row);
2853
2854                 if (row->pos <= last
2855                     && !row->par->table
2856                     && last != vis2log(last)
2857                     && row->par->IsLineSeparator(last)) {
2858                         if (!(main_body > 0 && main_body-1 == last))
2859                                 x -= fill_separator+SingleWidth(row->par,last);
2860                 } else if (main_body > 0 &&
2861                            (main_body-1 > last || 
2862                             !row->par->IsLineSeparator(main_body-1))) {
2863                         LyXLayout const & layout = textclasslist.Style(parameters->textclass,
2864                                                                        row->par->GetLayout());
2865                         x += GetFont(row->par, -2).stringWidth(layout.labelsep);
2866                         if (main_body-1 <= last)
2867                                 x += fill_label_hfill;
2868                 }
2869         }
2870 }
2871       
2872 /* important for the screen */
2873
2874
2875 /* the cursor set functions have a special mechanism. When they
2876 * realize, that you left an empty paragraph, they will delete it.
2877 * They also delete the corresponding row */
2878
2879 void LyXText::CursorRightOneWord() const
2880 {
2881         // treat floats, HFills and Insets as words
2882         LyXCursor tmpcursor = cursor;
2883 #warning See comment on top of text.C
2884
2885         if (tmpcursor.pos == tmpcursor.par->Last()
2886             && tmpcursor.par->Next())
2887         {
2888                         tmpcursor.par = tmpcursor.par->Next();
2889                         tmpcursor.pos = 0;
2890         } else {
2891                 int steps = 0;
2892
2893                 // Skip through initial nonword stuff.
2894                 while ( tmpcursor.pos < tmpcursor.par->Last() &&
2895                         ! tmpcursor.par->IsWord( tmpcursor.pos ) ) 
2896                 {
2897                   //    printf("Current pos1 %d", tmpcursor.pos) ;
2898                         tmpcursor.pos++;
2899                         ++steps;
2900                 }
2901                 // Advance through word.
2902                 while ( tmpcursor.pos < tmpcursor.par->Last() &&
2903                         tmpcursor.par->IsWord( tmpcursor.pos ) )
2904                 {
2905                   //     printf("Current pos2 %d", tmpcursor.pos) ;
2906                         tmpcursor.pos++;
2907                         ++steps;
2908                 }
2909         }
2910         SetCursor(tmpcursor.par, tmpcursor.pos);
2911 }
2912
2913
2914 void LyXText::CursorTab() const
2915 {
2916     if (cursor.par->table) {
2917         int cell = NumberOfCell(cursor.par, cursor.pos);
2918         while(cursor.par->table->IsContRow(cell)) {
2919             CursorUp();
2920             cell = NumberOfCell(cursor.par, cursor.pos);
2921         }
2922         if (cursor.par->table->ShouldBeVeryLastCell(cell))
2923             TableFeatures(LyXTable::APPEND_ROW);
2924     }
2925     LyXCursor tmpcursor = cursor;
2926     while (tmpcursor.pos < tmpcursor.par->Last()
2927            && !tmpcursor.par->IsNewline(tmpcursor.pos))
2928         tmpcursor.pos++;
2929    
2930     if (tmpcursor.pos == tmpcursor.par->Last()){
2931         if (tmpcursor.par->Next()) {
2932             tmpcursor.par = tmpcursor.par->Next();
2933             tmpcursor.pos = 0;
2934         }
2935     }
2936     else
2937         tmpcursor.pos++;
2938     SetCursor(tmpcursor.par, tmpcursor.pos);
2939     if (cursor.par->table) {
2940         int cell = NumberOfCell(cursor.par, cursor.pos);
2941         while (cursor.par->table->IsContRow(cell) &&
2942                !cursor.par->table->ShouldBeVeryLastCell(cell)) {
2943             tmpcursor = cursor;
2944             while (tmpcursor.pos < tmpcursor.par->Last()
2945                    && !tmpcursor.par->IsNewline(tmpcursor.pos))
2946                 tmpcursor.pos++;
2947    
2948             if (tmpcursor.pos == tmpcursor.par->Last()){
2949                 if (tmpcursor.par->Next()) {
2950                     tmpcursor.par = tmpcursor.par->Next();
2951                     tmpcursor.pos = 0;
2952                 }
2953             }
2954             else
2955                 tmpcursor.pos++;
2956             SetCursor(tmpcursor.par, tmpcursor.pos);
2957             cell = NumberOfCell(cursor.par, cursor.pos);
2958         }
2959     }
2960 }
2961
2962
2963 /* -------> Skip initial whitespace at end of word and move cursor to *start*
2964             of prior word, not to end of next prior word. */
2965
2966 void LyXText::CursorLeftOneWord()  const
2967 {
2968         // treat HFills, floats and Insets as words
2969         LyXCursor tmpcursor = cursor;
2970         while (tmpcursor.pos 
2971                && (tmpcursor.par->IsSeparator(tmpcursor.pos - 1) 
2972                    || tmpcursor.par->IsKomma(tmpcursor.pos - 1))
2973                && !(tmpcursor.par->IsHfill(tmpcursor.pos - 1)
2974                     || tmpcursor.par->IsFloat(tmpcursor.pos - 1)
2975                     || tmpcursor.par->IsInset(tmpcursor.pos - 1)))
2976                 tmpcursor.pos--;
2977
2978         if (tmpcursor.pos
2979             && (tmpcursor.par->IsInset(tmpcursor.pos - 1)
2980                 || tmpcursor.par->IsFloat(tmpcursor.pos - 1)
2981                 || tmpcursor.par->IsHfill(tmpcursor.pos - 1))) {
2982                 tmpcursor.pos--;
2983         } else if (!tmpcursor.pos) {
2984                 if (tmpcursor.par->Previous()){
2985                         tmpcursor.par = tmpcursor.par->Previous();
2986                         tmpcursor.pos = tmpcursor.par->Last();
2987                 }
2988         } else {                // Here, tmpcursor != 0 
2989                 while (tmpcursor.pos > 0 &&
2990                        tmpcursor.par->IsWord(tmpcursor.pos-1) )
2991                         tmpcursor.pos-- ;
2992         }
2993         SetCursor(tmpcursor.par, tmpcursor.pos);
2994 }
2995
2996 /* -------> Select current word. This depends on behaviour of CursorLeftOneWord(), so it is
2997                         patched as well. */
2998
2999 void LyXText::SelectWord() 
3000 {
3001         /* Move cursor to the beginning, when not already there. */
3002         if ( cursor.pos
3003              && !cursor.par->IsSeparator(cursor.pos-1)
3004              && !cursor.par->IsKomma(cursor.pos-1) )
3005                 CursorLeftOneWord();
3006
3007         /* set the sel cursor */
3008         sel_cursor = cursor;
3009
3010         while ( cursor.pos < cursor.par->Last()
3011                         && !cursor.par->IsSeparator(cursor.pos)
3012                         && !cursor.par->IsKomma(cursor.pos) )
3013                 cursor.pos++;
3014         SetCursor( cursor.par, cursor.pos );
3015         
3016         /* finally set the selection */ 
3017         SetSelection();
3018 }
3019
3020
3021 /* -------> Select the word currently under the cursor when:
3022                         1: no selection is currently set,
3023                         2: the cursor is not at the borders of the word. */
3024
3025 int LyXText::SelectWordWhenUnderCursor() 
3026 {
3027         if ( selection ) return 0;
3028         if ( cursor.pos < cursor.par->Last()
3029                  && !cursor.par->IsSeparator(cursor.pos)
3030                  && !cursor.par->IsKomma(cursor.pos)
3031                  && cursor.pos 
3032                  && !cursor.par->IsSeparator(cursor.pos -1)
3033                  && !cursor.par->IsKomma(cursor.pos -1) ) {
3034                 SelectWord();
3035                 return 1;
3036         }
3037         return 0;
3038 }
3039
3040
3041 // This function is only used by the spellchecker for NextWord().
3042 // It doesn't handle LYX_ACCENTs and probably never will.
3043 char * LyXText::SelectNextWord(float & value)
3044 {
3045         LyXParagraph * tmppar = cursor.par;
3046         
3047         // If this is not the very first word, skip rest of
3048         // current word because we are probably in the middle
3049         // of a word if there is text here.
3050         if (cursor.pos || cursor.par->previous) {
3051                 while (cursor.pos < cursor.par->Last()
3052                        && cursor.par->IsLetter(cursor.pos))
3053                         cursor.pos++;
3054         }
3055         // Now, skip until we have real text (will jump paragraphs)
3056         while ((cursor.par->Last() > cursor.pos
3057                 && (!cursor.par->IsLetter(cursor.pos)
3058                     || cursor.par->getFont(cursor.pos).latex() == LyXFont::ON))
3059                || (cursor.par->Last() == cursor.pos
3060                    && cursor.par->Next())){
3061                 if (cursor.pos == cursor.par->Last()) {
3062                         cursor.par = cursor.par->Next();
3063                         cursor.pos = 0;
3064                 }
3065                 else
3066                         cursor.pos++;
3067         }
3068   
3069         // Update the value if we changed paragraphs
3070         if (cursor.par != tmppar){
3071                 SetCursor(cursor.par, cursor.pos);
3072                 value = float(cursor.y)/float(height);
3073         }
3074
3075         /* Start the selection from here */
3076         sel_cursor = cursor;
3077
3078 #ifdef HAVE_SSTREAM
3079         ostringstream latex;
3080 #else
3081         ostrstream latex;
3082 #endif
3083         /* and find the end of the word 
3084            (optional hyphens are part of a word) */
3085         while (cursor.pos < cursor.par->Last()
3086                && (cursor.par->IsLetter(cursor.pos)) 
3087                    || (cursor.par->GetChar(cursor.pos) == LyXParagraph::META_INSET
3088                        && cursor.par->GetInset(cursor.pos) != 0
3089                        && cursor.par->GetInset(cursor.pos)->Latex(latex, 0, false) == 0
3090 #ifdef HAVE_SSTREAM
3091                        && latex.str() == "\\-"
3092 #else
3093                 && string(latex.str(), 3) == "\\-" // this is not nice at all
3094 #endif
3095                            ))
3096                 cursor.pos++;
3097
3098 #ifndef HAVE_SSTREAM
3099         delete [] latex.str();
3100 #endif
3101         // Finally, we copy the word to a string and return it
3102         char * str = 0;
3103
3104         if (sel_cursor.pos < cursor.pos) {
3105                 str = new char [cursor.pos - sel_cursor.pos + 2];
3106                 LyXParagraph::size_type i, j;
3107                 for (i = sel_cursor.pos, j = 0; i < cursor.pos; ++i) {
3108                         if (cursor.par->GetChar(i) != LyXParagraph::META_INSET)
3109                                 str[j++] = cursor.par->GetChar(i);
3110                 }
3111                 str[j] = '\0';
3112         }
3113         return str;
3114 }
3115
3116
3117 // This one is also only for the spellchecker
3118 void LyXText::SelectSelectedWord()
3119 {
3120         /* move cursor to the beginning */
3121         SetCursor(sel_cursor.par, sel_cursor.pos);
3122         
3123         /* set the sel cursor */
3124         sel_cursor = cursor;
3125
3126 #ifdef HAVE_SSTREAM
3127         ostringstream latex;
3128 #else
3129         ostrstream latex;
3130 #endif
3131         
3132         /* now find the end of the word */
3133         while (cursor.pos < cursor.par->Last()
3134                && (cursor.par->IsLetter(cursor.pos)
3135                    || (cursor.par->GetChar(cursor.pos) == LyXParagraph::META_INSET
3136                        && cursor.par->GetInset(cursor.pos) != 0
3137                        && cursor.par->GetInset(cursor.pos)->Latex(latex, 0, false) == 0
3138 #ifdef HAVE_SSTREAM
3139                        && latex.str() == "\\-"
3140 #else
3141                        && string(latex.str(), 3) == "\\-"
3142 #endif
3143                            )))
3144                 cursor.pos++;
3145         
3146 #ifndef HAVE_SSTREAM
3147         delete [] latex.str();
3148 #endif
3149         SetCursor(cursor.par, cursor.pos);
3150         
3151         /* finally set the selection */ 
3152         SetSelection();
3153 }
3154
3155
3156 /* -------> Delete from cursor up to the end of the current or next word. */
3157 void LyXText::DeleteWordForward()
3158 {
3159         LyXCursor tmpcursor = cursor;
3160         
3161         if (!cursor.par->Last())
3162                 CursorRight();
3163 #warning See comment on top of text.C
3164         else {
3165                 /* -------> Skip initial non-word stuff. */
3166                 while ( cursor.pos < cursor.par->Last() 
3167                         && (cursor.par->IsSeparator(cursor.pos)
3168                             || cursor.par->IsKomma(cursor.pos)) )
3169                         cursor.pos++;
3170                 
3171                 SetCursorIntern(cursor.par, cursor.pos);
3172                 selection = True; // to avoid deletion 
3173                 CursorRightOneWord();
3174                 sel_cursor = cursor;
3175                 cursor = tmpcursor;
3176                 SetSelection(); 
3177                 
3178                 /* -----> Great, CutSelection() gets rid of multiple spaces. */
3179                 CutSelection();
3180         }
3181 }
3182
3183
3184 /* -------> Delete from cursor to start of current or prior word. */
3185 void LyXText::DeleteWordBackward()
3186 {
3187        LyXCursor tmpcursor = cursor;
3188        if (!cursor.par->Last())
3189          CursorLeft();
3190 #warning See comment on top of text.C
3191        else{
3192          selection = true; // to avoid deletion 
3193          CursorLeftOneWord();
3194          sel_cursor = cursor;
3195          cursor = tmpcursor;
3196          SetSelection();
3197          CutSelection();
3198        }
3199 }
3200
3201
3202 /* -------> Kill to end of line. */
3203 void LyXText::DeleteLineForward()
3204 {
3205         LyXCursor tmpcursor = cursor;
3206         if (!cursor.par->Last())
3207                 CursorRight();
3208 #warning See comment on top of text.C
3209         else {
3210                 CursorEnd();
3211                 sel_cursor = cursor;
3212                 cursor = tmpcursor;
3213                 SetSelection();
3214                 if (selection == false) {
3215                         DeleteWordForward();
3216                 } else {
3217                         CutSelection();
3218                 }
3219         }
3220 }
3221
3222
3223 // Change the case of a word at cursor position. The meaning of action
3224 // is:
3225 // 0  change to lowercase
3226 // 1  capitalize word
3227 // 2  change to uppercase
3228 // This function directly manipulates LyXParagraph::text because there
3229 // is no LyXParagraph::SetChar currently. I did what I could to ensure
3230 // that it is correct. I guess part of it should be moved to
3231 // LyXParagraph, but it will have to change for 1.1 anyway. At least
3232 // it does not access outside of the allocated array as the older
3233 // version did. (JMarc) 
3234 void LyXText::ChangeWordCase(LyXText::TextCase action) 
3235 {
3236         LyXParagraph * tmppar = cursor.par->ParFromPos(cursor.pos);
3237
3238         SetUndo(Undo::FINISH, tmppar->previous, tmppar->next); 
3239
3240         LyXParagraph::size_type tmppos = 
3241                 cursor.par->PositionInParFromPos(cursor.pos);
3242         while (tmppos < tmppar->size()) {
3243                 //unsigned char c = tmppar->text[tmppos];
3244                 unsigned char c = tmppar->GetChar(tmppos);
3245                 if (IsKommaChar(c) || IsLineSeparatorChar(c))
3246                         break;
3247                 if (c != LyXParagraph::META_INSET) {
3248                         switch (action) {
3249                         case text_lowercase:
3250                                 c = tolower(c);
3251                                 break;
3252                         case text_capitalization:
3253                                 c = toupper(c);
3254                                 action = text_lowercase;
3255                                 break;
3256                         case text_uppercase:
3257                                 c = toupper(c);
3258                                 break;
3259                         }
3260                 }
3261                 
3262                 //tmppar->text[tmppos] = c;
3263                 tmppar->SetChar(tmppos, c);
3264                 ++tmppos;
3265         }
3266         CheckParagraph(tmppar, tmppos);
3267         CursorRightOneWord();
3268 }
3269
3270
3271 void LyXText::Delete()
3272 {
3273         // this is a very easy implementation
3274
3275         LyXCursor old_cursor = cursor;
3276         int old_cur_par_id = old_cursor.par->id();
3277         int old_cur_par_prev_id = old_cursor.par->previous ?
3278                 old_cursor.par->previous->id() : 0;
3279         
3280         // just move to the right
3281         CursorRightIntern();
3282
3283 #warning Look at the comment here.
3284         // This check is not very good...
3285         // The CursorRightIntern calls DeleteEmptyParagrapgMechanism
3286         // and that can very well delete the par or par->previous in
3287         // old_cursor. Will a solution where we compare paragraph id's
3288         //work better?
3289 #if 1
3290         if ((cursor.par->previous ? cursor.par->previous->id() : 0)
3291             == old_cur_par_prev_id
3292             && cursor.par->id() != old_cur_par_id)
3293                 return; // delete-empty-paragraph-mechanism has done it
3294 #else
3295         if (cursor.par->previous == old_cursor.par->previous
3296             && cursor.par != old_cursor.par)
3297                 return; // delete-empty-paragraph-mechanism has done it
3298 #endif
3299         // if you had success make a backspace
3300         if (old_cursor.par != cursor.par || old_cursor.pos != cursor.pos) {
3301                 LyXCursor tmpcursor = cursor;
3302                 cursor = old_cursor; // to make sure undo gets the right cursor position
3303                 SetUndo(Undo::DELETE, 
3304                         cursor.par->ParFromPos(cursor.pos)->previous, 
3305                         cursor.par->ParFromPos(cursor.pos)->next); 
3306                 cursor = tmpcursor;
3307                 Backspace();
3308         }
3309 }
3310
3311
3312 void LyXText::Backspace()
3313 {
3314         DebugTracer trc1("LyXText::Backspace");
3315         
3316         /* table stuff -- begin */
3317         if (cursor.par->table) {
3318                 BackspaceInTable();
3319                 return;
3320         }
3321         /* table stuff -- end */
3322         
3323         LyXFont rawtmpfont = current_font;
3324         LyXFont realtmpfont = real_current_font;
3325    
3326         // Get the font that is used to calculate the baselineskip
3327         int const lastpos = cursor.par->Last();
3328         LyXFont rawparfont = cursor.par->GetFontSettings(lastpos - 1);
3329
3330         if (cursor.pos == 0) {
3331                 DebugTracer trc("LyXText::Backspace cursor.pos == 0");
3332                 
3333                 // The cursor is at the beginning of a paragraph, so the the backspace
3334                 // will collapse two paragraphs into one.
3335                 
3336                 // we may paste some paragraphs
3337       
3338                 // is it an empty paragraph?
3339       
3340                 if ((lastpos == 0
3341                      || (lastpos == 1 && cursor.par->IsSeparator(0)))
3342                     && !(cursor.par->Next() 
3343                          && cursor.par->footnoteflag == LyXParagraph::NO_FOOTNOTE
3344                          && cursor.par->Next()->footnoteflag == LyXParagraph::OPEN_FOOTNOTE)) {
3345                         // This is an empty paragraph and we delete it just by moving the curosr one step
3346                         // left and let the DeleteEmptyParagraphMechanism handle the actual deleteion
3347                         // of the paragraph.
3348                         
3349                         if (cursor.par->previous) {
3350                                 LyXParagraph * tmppar = cursor.par->previous->FirstPhysicalPar();
3351                                 if (cursor.par->GetLayout() == tmppar->GetLayout()
3352                                     && cursor.par->footnoteflag == tmppar->footnoteflag
3353                                     && cursor.par->GetAlign() == tmppar->GetAlign()) {
3354                                         // Inherit botom DTD from the paragraph below.
3355                                         // (the one we are deleting)
3356                                         tmppar->line_bottom = cursor.par->line_bottom;
3357                                         tmppar->added_space_bottom = cursor.par->added_space_bottom;
3358                                         tmppar->pagebreak_bottom = cursor.par->pagebreak_bottom;
3359                                 }
3360                                 
3361                                 CursorLeftIntern();
3362                      
3363                                 // the layout things can change the height of a row !
3364                                 int tmpheight = cursor.row->height;
3365                                 SetHeightOfRow(cursor.row);
3366                                 if (cursor.row->height != tmpheight) {
3367                                         refresh_y = cursor.y - cursor.row->baseline;
3368                                         refresh_row = cursor.row;
3369                                         status = LyXText::NEED_MORE_REFRESH;
3370                                 }
3371                                 return;
3372                         }
3373                 }
3374                 
3375                 if (cursor.par->ParFromPos(cursor.pos)->previous){
3376                         SetUndo(Undo::DELETE,
3377                                 cursor.par->ParFromPos(cursor.pos)->previous->previous,
3378                                 cursor.par->ParFromPos(cursor.pos)->next);
3379                 }
3380                 
3381                 LyXParagraph * tmppar = cursor.par;
3382                 Row * tmprow = cursor.row;
3383
3384                 // We used to do CursorLeftIntern() here, but it is
3385                 // not a good idea since it triggers the auto-delete
3386                 // mechanism. So we do a CursorLeftIntern()-lite,
3387                 // without the dreaded mechanism. (JMarc)
3388                 if (cursor.pos > 0) {
3389                         SetCursorIntern(cursor.par, cursor.pos - 1);
3390                 }
3391                 else if (cursor.par->Previous()) { 
3392                         // steps into the above paragraph.
3393                         SetCursorIntern(cursor.par->Previous(), 
3394                                         cursor.par->Previous()->Last());
3395                 }
3396
3397
3398 #warning See comment on top of text.C
3399                 /* Pasting is not allowed, if the paragraphs have different
3400                    layout. I think it is a real bug of all other
3401                    word processors to allow it. It confuses the user.
3402                    Even so with a footnote paragraph and a non-footnote
3403                    paragraph. I will not allow pasting in this case, 
3404                    because the user would be confused if the footnote behaves 
3405                    different wether it is open or closed.
3406                   
3407                    Correction: Pasting is always allowed with standard-layout
3408                 */
3409                 if (cursor.par != tmppar
3410                     && (cursor.par->GetLayout() == tmppar->GetLayout()
3411                         || tmppar->GetLayout() == 0 /*standard*/)
3412                     && cursor.par->footnoteflag == tmppar->footnoteflag
3413                     /* table stuff -- begin*/
3414                     && !cursor.par->table /* no pasting of tables */ 
3415                     /* table stuff -- end*/
3416                     && cursor.par->GetAlign() == tmppar->GetAlign()) {
3417
3418                         RemoveParagraph(tmprow);
3419                         RemoveRow(tmprow);
3420                         cursor.par->PasteParagraph();
3421                         
3422                         if (!cursor.pos || !cursor.par->IsSeparator(cursor.pos - 1))
3423                                 ; //cursor.par->InsertChar(cursor.pos, ' ');
3424                         // strangely enough it seems that commenting out the line above removes
3425                         // most or all of the segfaults. I will however also try to move the
3426                         // two Remove... lines in front of the PasteParagraph too.
3427                         else
3428                                 if (cursor.pos)
3429                                         cursor.pos--;
3430                         
3431                         status = LyXText::NEED_MORE_REFRESH;
3432                         refresh_row = cursor.row;
3433                         refresh_y = cursor.y - cursor.row->baseline;
3434                         
3435                         // remove the lost paragraph
3436                         // This one is not safe, since the paragraph that the tmprow and the
3437                         // following rows belong to has been deleted by the PasteParagraph
3438                         // above. The question is... could this be moved in front of the
3439                         // PasteParagraph?
3440                         //RemoveParagraph(tmprow);
3441                         //RemoveRow(tmprow);  
3442                         
3443                         AppendParagraph(cursor.row); // This rebuilds the rows.
3444                         UpdateCounters(cursor.row);
3445                         
3446                         // the row may have changed, block, hfills etc.
3447                         SetCursor(cursor.par, cursor.pos);
3448                 }
3449         } else {
3450                 DebugTracer trc("LyXText::Backspace normal backspace");
3451                 
3452                 /* this is the code for a normal backspace, not pasting
3453                  * any paragraphs */ 
3454                 SetUndo(Undo::DELETE, 
3455                         cursor.par->ParFromPos(cursor.pos)->previous, 
3456                         cursor.par->ParFromPos(cursor.pos)->next); 
3457                 // We used to do CursorLeftIntern() here, but it is
3458                 // not a good idea since it triggers the auto-delete
3459                 // mechanism. So we do a CursorLeftIntern()-lite,
3460                 // without the dreaded mechanism. (JMarc)
3461                 if (cursor.pos > 0) {
3462                         SetCursorIntern(cursor.par, cursor.pos - 1);
3463                 }
3464                 else if (cursor.par->Previous()) { 
3465                         // steps into the above paragraph.
3466                         SetCursorIntern(cursor.par->Previous(), 
3467                                         cursor.par->Previous()->Last());
3468                 }
3469 //              CursorLeftIntern();
3470                 
3471                 // some insets are undeletable here
3472                 if (cursor.par->GetChar(cursor.pos) == LyXParagraph::META_INSET) {
3473                         if (!cursor.par->GetInset(cursor.pos)->Deletable())
3474                                 return; 
3475                         // force complete redo when erasing display insets
3476                         // this is a cruel mathod but save..... Matthias 
3477                         if (cursor.par->GetInset(cursor.pos)->display()){
3478                                 cursor.par->Erase(cursor.pos);
3479                                 RedoParagraph();
3480                                 return;
3481                         }
3482                 }
3483                 
3484                 Row * row = cursor.row;
3485                 long y = cursor.y - row->baseline;
3486                 LyXParagraph::size_type z;
3487                 /* remember that a space at the end of a row doesnt count
3488                  * when calculating the fill */ 
3489                 if (cursor.pos < RowLast(row) ||
3490                     !cursor.par->IsLineSeparator(cursor.pos)) {
3491                         row->fill += SingleWidth(cursor.par, cursor.pos);
3492                 }
3493                 
3494                 /* some special code when deleting a newline. This is similar
3495                  * to the behavior when pasting paragraphs */ 
3496                 if (cursor.pos && cursor.par->IsNewline(cursor.pos)) {
3497                         cursor.par->Erase(cursor.pos);
3498                         // refresh the positions
3499                         Row * tmprow = row;
3500                         while (tmprow->next && tmprow->next->par == row->par) {
3501                                 tmprow = tmprow->next;
3502                                 tmprow->pos--;
3503                         }
3504                         if (cursor.par->IsLineSeparator(cursor.pos - 1))
3505                                 cursor.pos--;
3506                         
3507                         if (cursor.pos < cursor.par->Last() && !cursor.par->IsSeparator(cursor.pos)) {
3508                                 cursor.par->InsertChar(cursor.pos, ' ');
3509                                 // refresh the positions
3510                                 tmprow = row;
3511                                 while (tmprow->next && tmprow->next->par == row->par) {
3512                                         tmprow = tmprow->next;
3513                                         tmprow->pos++;
3514                                 }
3515                         }
3516                 } else {
3517                         cursor.par->Erase(cursor.pos);
3518                         
3519                         // refresh the positions
3520                         Row * tmprow = row;
3521                         while (tmprow->next && tmprow->next->par == row->par) {
3522                                 tmprow = tmprow->next;
3523                                 tmprow->pos--;
3524                         }
3525
3526 #ifndef FIX_DOUBLE_SPACE
3527                         // delete superfluous blanks 
3528                         if (cursor.pos < cursor.par->Last() - 1 &&
3529                             (cursor.par->IsLineSeparator(cursor.pos))) {
3530                                 
3531                                 if (cursor.pos == BeginningOfMainBody(cursor.par)
3532                                     || !cursor.pos 
3533                                     || cursor.par->IsLineSeparator(cursor.pos - 1)) {
3534                                         cursor.par->Erase(cursor.pos);
3535                                         // refresh the positions
3536                                         tmprow = row;
3537                                         while (tmprow->next && 
3538                                                tmprow->next->par == row->par) {
3539                                                 tmprow = tmprow->next;
3540                                                 tmprow->pos--;
3541                                         }
3542                                         if (cursor.pos)   // move one character left
3543                                                 cursor.pos--;
3544                                 }
3545                         }
3546 #endif
3547                         
3548                         // delete newlines at the beginning of paragraphs
3549                         while (cursor.par->Last() &&
3550                                cursor.par->IsNewline(cursor.pos) &&
3551                                cursor.pos == BeginningOfMainBody(cursor.par)) {
3552                                 cursor.par->Erase(cursor.pos);
3553                                 // refresh the positions
3554                                 tmprow = row;
3555                                 while (tmprow->next && 
3556                                        tmprow->next->par == row->par) {
3557                                         tmprow = tmprow->next;
3558                                         tmprow->pos--;
3559                                 }
3560                         }
3561                 }
3562                 
3563                 // is there a break one row above
3564                 if (row->previous && row->previous->par == row->par) {
3565                         z = NextBreakPoint(row->previous, paperwidth);
3566                         if ( z >= row->pos) {
3567                                 row->pos = z + 1;
3568                                 
3569                                 Row * tmprow = row->previous;
3570                                 
3571                                 // maybe the current row is now empty
3572                                 if (row->pos >= row->par->Last()) {
3573                                         // remove it
3574                                         RemoveRow(row);
3575                                         need_break_row = 0;
3576                                 } else {
3577                                         BreakAgainOneRow(row);
3578                                         if (row->next && row->next->par == row->par)
3579                                                 need_break_row = row->next;
3580                                         else
3581                                                 need_break_row = 0;
3582                                 }
3583                                 
3584                                 // set the dimensions of the row above
3585                                 y -= tmprow->height;
3586                                 tmprow->fill = Fill(tmprow, paperwidth);
3587                                 SetHeightOfRow(tmprow);
3588                                 
3589                                 refresh_y = y;
3590                                 refresh_row = tmprow;
3591                                 status = LyXText::NEED_MORE_REFRESH;
3592                                 current_font = rawtmpfont;
3593                                 real_current_font = realtmpfont;
3594                                 SetCursor(cursor.par, cursor.pos, false);
3595                                 // check, whether the last character's font has changed.
3596                                 rawtmpfont = cursor.par->GetFontSettings(cursor.par->Last() - 1);
3597                                 if (rawparfont != rawtmpfont)
3598                                         RedoHeightOfParagraph(cursor);
3599                                 return;
3600                         }
3601                 }
3602                 
3603                 // break the cursor row again
3604                 z = NextBreakPoint(row, paperwidth);
3605                 
3606                 if (z != RowLast(row) || 
3607                     (row->next && row->next->par == row->par &&
3608                      RowLast(row) == row->par->Last() - 1)){
3609                         
3610                         /* it can happen that a paragraph loses one row
3611                          * without a real breakup. This is when a word
3612                          * is to long to be broken. Well, I don t care this 
3613                          * hack ;-) */ 
3614                         if (row->next && row->next->par == row->par &&
3615                             RowLast(row) == row->par->Last() - 1)
3616                                 RemoveRow(row->next);
3617                         
3618                         refresh_y = y;
3619                         refresh_row = row;
3620                         status = LyXText::NEED_MORE_REFRESH;
3621                         
3622                         BreakAgainOneRow(row);
3623                         current_font = rawtmpfont; 
3624                         real_current_font = realtmpfont;
3625                         SetCursor(cursor.par, cursor.pos, false);
3626                         // cursor MUST be in row now
3627                         
3628                         if (row->next && row->next->par == row->par)
3629                                 need_break_row = row->next;
3630                         else
3631                                 need_break_row = 0;
3632                 } else  {
3633                         // set the dimensions of the row
3634                         row->fill = Fill(row, paperwidth);
3635                         int tmpheight = row->height;
3636                         SetHeightOfRow(row);
3637                         if (tmpheight == row->height)
3638                                 status = LyXText::NEED_VERY_LITTLE_REFRESH;
3639                         else
3640                                 status = LyXText::NEED_MORE_REFRESH;
3641                         refresh_y = y;
3642                         refresh_row = row;
3643                         current_font = rawtmpfont; 
3644                         real_current_font = realtmpfont;
3645                         SetCursor(cursor.par, cursor.pos, false);
3646                 }
3647         }
3648         DebugTracer trc2("LyXText::Backspace wrap up");
3649         
3650         // restore the current font
3651         // That is what a user expects!
3652         current_font = rawtmpfont; 
3653         real_current_font = realtmpfont;
3654         
3655         // check, wether the last characters font has changed.
3656         rawtmpfont = cursor.par->GetFontSettings(cursor.par->Last() - 1);
3657         if (rawparfont != rawtmpfont) {
3658                 RedoHeightOfParagraph(cursor);
3659         } else {
3660                 // now the special right address boxes
3661                 if (textclasslist.Style(parameters->textclass,
3662                                         cursor.par->GetLayout()).margintype == MARGIN_RIGHT_ADDRESS_BOX) {
3663                         RedoDrawingOfParagraph(cursor); 
3664                 }
3665         }
3666 }
3667
3668
3669 void LyXText::GetVisibleRow(int offset, 
3670                             Row * row_ptr, long y)
3671 {
3672         /* returns a printed row */
3673         Painter & pain = owner_->painter();
3674         
3675         LyXDirection direction = row_ptr->par->getParDirection();
3676         LyXParagraph::size_type vpos, pos, pos_end;
3677         float x, tmpx;
3678         int y_top, y_bottom;
3679         float fill_separator, fill_hfill, fill_label_hfill;
3680         LyXParagraph * par, * firstpar;
3681         LyXFont font;
3682         int maxdesc;
3683         if (row_ptr->height <= 0) {
3684                 lyxerr << "LYX_ERROR: row.height: " << row_ptr->height << endl;
3685                 return;
3686         }
3687         PrepareToPrint(row_ptr, x, fill_separator,
3688                        fill_hfill, fill_label_hfill);
3689         
3690         /* initialize the pixmap */
3691         
3692         pain.fillRectangle(0, offset, paperwidth, row_ptr->height);
3693         
3694         if (selection) {
3695                 /* selection code */ 
3696                 if (sel_start_cursor.row == row_ptr &&
3697                     sel_end_cursor.row == row_ptr) {
3698                         if (sel_start_cursor.x < sel_end_cursor.x)
3699                                 pain.fillRectangle(sel_start_cursor.x, offset,
3700                                                    sel_end_cursor.x - sel_start_cursor.x,
3701                                                    row_ptr->height,
3702                                                    LColor::selection);
3703                         else
3704                                 pain.fillRectangle(sel_end_cursor.x, offset,
3705                                                    sel_start_cursor.x - sel_end_cursor.x,
3706                                                    row_ptr->height,
3707                                                    LColor::selection);
3708                 } else if (sel_start_cursor.row == row_ptr) {
3709                         if (direction == LYX_DIR_LEFT_TO_RIGHT)
3710                                 pain.fillRectangle(sel_start_cursor.x, offset,
3711                                                    paperwidth - sel_start_cursor.x,
3712                                                    row_ptr->height,
3713                                                    LColor::selection);
3714                         else
3715                                 pain.fillRectangle(0, offset,
3716                                                    sel_start_cursor.x,
3717                                                    row_ptr->height,
3718                                                    LColor::selection);
3719                 } else if (sel_end_cursor.row == row_ptr) {
3720                         if (direction == LYX_DIR_LEFT_TO_RIGHT)
3721                                 pain.fillRectangle(0, offset,
3722                                                    sel_end_cursor.x,
3723                                                    row_ptr->height,
3724                                                    LColor::selection);
3725                         else
3726                                 pain.fillRectangle(sel_end_cursor.x, offset,
3727                                                    paperwidth - sel_end_cursor.x,
3728                                                    row_ptr->height,
3729                                                    LColor::selection);
3730                         
3731                 } else if (y > sel_start_cursor.y && y < sel_end_cursor.y) {
3732                         pain.fillRectangle(0, offset,
3733                                            paperwidth, row_ptr->height,
3734                                            LColor::selection);
3735                 }
3736         }
3737         
3738         if (row_ptr->par->appendix){
3739                 pain.line(1, offset,
3740                           1, offset + row_ptr->height,
3741                           LColor::appendixline);
3742                 pain.line(paperwidth - 2, offset,
3743                           paperwidth - 2, offset + row_ptr->height,
3744                           LColor::appendixline);
3745         }
3746         
3747         if (row_ptr->par->pextra_type == LyXParagraph::PEXTRA_MINIPAGE) {
3748                 /* draw a marker at the left margin! */ 
3749                 LyXFont font = GetFont(row_ptr->par, 0);
3750                 int asc = font.maxAscent();
3751                 int x = (LYX_PAPER_MARGIN - font.width('|')) / 2;
3752                 int y1 = (offset + row_ptr->baseline);
3753                 int y2 = (offset + row_ptr->baseline) - asc;
3754                 pain.line(x, y1, x, y2, LColor::minipageline);
3755         }       
3756         if (row_ptr->par->footnoteflag == LyXParagraph::OPEN_FOOTNOTE) {
3757                 LyXFont font(LyXFont::ALL_SANE);
3758                 font.setSize(LyXFont::SIZE_FOOTNOTE);
3759                 font.setColor(LColor::footnote);
3760                 
3761                 int box_x = LYX_PAPER_MARGIN;
3762                 box_x += font.textWidth(" wide-tab ", 10);
3763                 if (row_ptr->previous && 
3764                     row_ptr->previous->par->footnoteflag != LyXParagraph::OPEN_FOOTNOTE){
3765                         string fs;
3766                         switch (row_ptr->par->footnotekind) {
3767                         case LyXParagraph::MARGIN:
3768                                 fs = " margin";
3769                                 break;
3770                         case LyXParagraph::FIG:
3771                                 fs = " fig";
3772                                 break;
3773                         case LyXParagraph::TAB:
3774                                 fs = " tab";
3775                                 break;
3776                         case LyXParagraph::WIDE_FIG:
3777                                 fs = " wide-fig";
3778                                 break;
3779                         case LyXParagraph::WIDE_TAB:
3780                                 fs = " wide-tab";
3781                                 break;
3782                         case LyXParagraph::ALGORITHM:
3783                                 fs = " alg";
3784                                 break;
3785                         case LyXParagraph::FOOTNOTE:
3786                                 fs = " foot";
3787                                 break;
3788                         }
3789                         
3790                         pain.fillRectangle(LYX_PAPER_MARGIN,
3791                                            offset + 1,
3792                                            box_x - LYX_PAPER_MARGIN,
3793                                            int(font.maxAscent()
3794                                                + font.maxDescent()),
3795                                            LColor::footnotebg);
3796                         
3797                         pain.line(LYX_PAPER_MARGIN, offset,
3798                                   paperwidth - LYX_PAPER_MARGIN, offset,
3799                                   LColor::footnoteframe);
3800                         
3801                         pain.text(LYX_PAPER_MARGIN,
3802                                   offset + int(font.maxAscent()) + 1,
3803                                   fs, font);
3804                         
3805                         pain.line(LYX_PAPER_MARGIN, offset,
3806                                   LYX_PAPER_MARGIN,
3807                                   offset + int(font.maxAscent()
3808                                                + font.maxDescent()),
3809                                   LColor::footnoteframe);
3810                         
3811                         pain.line(LYX_PAPER_MARGIN,
3812                                   offset + int(font.maxAscent()
3813                                                + font.maxDescent()) + 1,
3814                                   box_x,
3815                                   offset + int(font.maxAscent()
3816                                                + font.maxDescent()) + 1,
3817                                   LColor::footnoteframe);
3818                         
3819                 }
3820                 
3821                 /* draw the open floats in a red box */
3822                 pain.line(box_x, offset,
3823                           box_x, offset + row_ptr->height,
3824                           LColor::footnoteframe);
3825                 
3826                 pain.line(paperwidth - LYX_PAPER_MARGIN,
3827                           offset,
3828                           paperwidth - LYX_PAPER_MARGIN,
3829                           offset + row_ptr->height,
3830                           LColor::footnoteframe);
3831         } else if (row_ptr->previous &&
3832                    row_ptr->previous->par->footnoteflag
3833                    == LyXParagraph::OPEN_FOOTNOTE) {
3834                 LyXFont font(LyXFont::ALL_SANE);
3835                 font.setSize(LyXFont::SIZE_FOOTNOTE);
3836                 
3837                 int box_x = LYX_PAPER_MARGIN;
3838                 box_x += font.textWidth(" wide-tab ", 10);
3839                 
3840                 pain.line(box_x, offset,
3841                           paperwidth - LYX_PAPER_MARGIN,
3842                           offset, LColor::footnote);
3843         }
3844         
3845         LyXLayout const & layout =
3846                 textclasslist.Style(parameters->textclass,
3847                                     row_ptr->par->GetLayout());
3848         firstpar = row_ptr->par->FirstPhysicalPar();
3849         
3850         y_top = 0;
3851         y_bottom = row_ptr->height;
3852         
3853         /* is it a first row? */ 
3854         if (row_ptr->pos == 0
3855             && row_ptr->par == firstpar) {
3856                 
3857                 /* start of appendix? */
3858                 if (row_ptr->par->start_of_appendix){
3859                         pain.line(1, offset,
3860                                   paperwidth - 2, offset,
3861                                   LColor::appendixline);
3862                 }
3863                 
3864                 /* think about the margins */ 
3865                 if (!row_ptr->previous)
3866                         y_top += LYX_PAPER_MARGIN;
3867                 
3868                 if (row_ptr->par->pagebreak_top){ /* draw a top pagebreak  */
3869 #if 0
3870                         pain.line(0, offset + y_top + 2 * DefaultHeight(),
3871                                   paperwidth,
3872                                   offset + y_top + 2 * DefaultHeight(),
3873                                   LColor::pagebreak, Painter::line_onoffdash);
3874 #else
3875                         LyXFont pb_font;
3876                         pb_font.setColor(LColor::pagebreak).decSize();
3877                         int w = 0, a = 0, d = 0;
3878                         pain.line(0, offset + y_top + 2*DefaultHeight(),
3879                                   paperwidth, 
3880                                   offset + y_top + 2*DefaultHeight(),
3881                                   LColor::pagebreak, 
3882                                   Painter::line_onoffdash)
3883                                 .rectText(0,
3884                                           0,
3885                                           _("Page Break (top)"),
3886                                           pb_font,
3887                                           LColor::background,
3888                                           LColor::background, false, w, a, d);
3889                         pain.rectText((paperwidth - w)/2,
3890                                       offset +y_top + 2*DefaultHeight() +d,
3891                                       _("Page Break (top)"),
3892                                       pb_font,
3893                                       LColor::background,
3894                                       LColor::background);
3895 #endif
3896                         y_top += 3 * DefaultHeight();
3897                 }
3898                 
3899                 if (row_ptr->par->added_space_top.kind() == VSpace::VFILL) {
3900                         /* draw a vfill top  */
3901                         pain.line(0, offset + 2 + y_top,
3902                                   LYX_PAPER_MARGIN, offset + 2 + y_top,
3903                                   LColor::vfillline);
3904                         
3905                         pain.line(0, offset + y_top + 3 * DefaultHeight(),
3906                                   LYX_PAPER_MARGIN,
3907                                   offset + y_top + 3 * DefaultHeight(),
3908                                   LColor::vfillline);
3909                         
3910                         pain.line(LYX_PAPER_MARGIN / 2, offset + 2 + y_top,
3911                                   LYX_PAPER_MARGIN / 2,
3912                                   offset + y_top + 3 * DefaultHeight(),
3913                                   LColor::vfillline);
3914                         
3915                         y_top += 3 * DefaultHeight();
3916                 }
3917                 
3918                 /* think about user added space */ 
3919                 y_top += int(row_ptr->par->added_space_top.inPixels(owner_));
3920                 
3921                 /* think about the parskip */ 
3922                 /* some parskips VERY EASY IMPLEMENTATION */ 
3923                 if (parameters->paragraph_separation == BufferParams::PARSEP_SKIP) {
3924                         if (layout.latextype == LATEX_PARAGRAPH
3925                             && firstpar->GetDepth() == 0
3926                             && firstpar->Previous())
3927                                 y_top += parameters->getDefSkip().inPixels(owner_);
3928                         else if (firstpar->Previous()
3929                                  && textclasslist.Style(parameters->textclass,
3930                                                         firstpar->Previous()->GetLayout()).latextype == LATEX_PARAGRAPH
3931                                  && firstpar->Previous()->GetDepth() == 0)
3932                                 // is it right to use defskip here, too? (AS) 
3933                                 y_top += parameters->getDefSkip().inPixels(owner_);
3934                 }
3935                 
3936                 if (row_ptr->par->line_top) {      /* draw a top line  */
3937                         y_top +=  GetFont(row_ptr->par, 0).ascent('x');
3938                         
3939                         pain.line(0, offset + y_top,
3940                                   paperwidth, offset + y_top,
3941                                   LColor::topline,
3942                                   Painter::line_solid,
3943                                   Painter::line_thick);
3944                         
3945                         y_top +=  GetFont(row_ptr->par, 0).ascent('x');
3946                 }
3947                 
3948                 /* should we print a label? */ 
3949                 if (layout.labeltype >= LABEL_STATIC
3950                     && (layout.labeltype != LABEL_STATIC
3951                         || layout.latextype != LATEX_ENVIRONMENT
3952                         || row_ptr->par->IsFirstInSequence())) {
3953                         font = GetFont(row_ptr->par, -2);
3954                         if (!row_ptr->par->GetLabestring().empty()) {
3955                                 tmpx = x;
3956                                 string tmpstring = row_ptr->par->GetLabestring();
3957                                 
3958                                 if (layout.labeltype == LABEL_COUNTER_CHAPTER) {
3959                                         if (parameters->secnumdepth >= 0){
3960                                                 /* this is special code for the chapter layout. This is printed in
3961                                                  * an extra row and has a pagebreak at the top. */
3962                                                 maxdesc = int(font.maxDescent() * layout.spacing.getValue() * parameters->spacing.getValue())
3963                                                         + int(layout.parsep) * DefaultHeight();
3964                                                 if (direction == LYX_DIR_RIGHT_TO_LEFT)
3965                                                         tmpx = paperwidth - LeftMargin(row_ptr) - 
3966                                                                 font.stringWidth(tmpstring);
3967                                                 pain.text(int(tmpx),
3968                                                           offset + row_ptr->baseline - row_ptr->ascent_of_text - maxdesc,
3969                                                           tmpstring, font);
3970                                         }
3971                                 } else {
3972                                         if (direction == LYX_DIR_LEFT_TO_RIGHT)
3973                                                 tmpx = x - font.stringWidth(layout.labelsep)
3974                                                         - font.stringWidth(tmpstring);
3975                                         else {
3976                                                 tmpx = paperwidth - LeftMargin(row_ptr)
3977                                                         + font.stringWidth(layout.labelsep);
3978                                                 if (row_ptr->par->footnoteflag == LyXParagraph::OPEN_FOOTNOTE)  {
3979                                                         LyXFont font(LyXFont::ALL_SANE);
3980                                                         font.setSize(LyXFont::SIZE_SMALL);
3981                                                         tmpx += font.textWidth("Mwide-figM", 10);
3982                                                 }
3983                                         }
3984                                         /* draw it! */
3985                                         pain.text(int(tmpx),
3986                                                   offset + row_ptr->baseline,
3987                                                   tmpstring, font);
3988                                 }
3989                         }
3990                         /* the labels at the top of an environment. More or less for bibliography */ 
3991                 } else if (layout.labeltype == LABEL_TOP_ENVIRONMENT ||
3992                            layout.labeltype == LABEL_BIBLIO ||
3993                            layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT) {
3994                         if (row_ptr->par->IsFirstInSequence()) {
3995                                 font = GetFont(row_ptr->par, -2);
3996                                 if (!row_ptr->par->GetLabestring().empty()) {
3997                                         string tmpstring = row_ptr->par->GetLabestring();
3998                                         
3999                                         maxdesc = int(font.maxDescent() * layout.spacing.getValue() * parameters->spacing.getValue()
4000                                                       + (layout.labelbottomsep * DefaultHeight()));
4001                                         
4002                                         tmpx = x;
4003                                         if (layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT){
4004                                                 tmpx = ( ((direction == LYX_DIR_LEFT_TO_RIGHT)
4005                                                           ? x : LeftMargin(row_ptr) )
4006                                                          + paperwidth - RightMargin(row_ptr) ) / 2; 
4007                                                 tmpx -= (font.stringWidth(tmpstring)/2);
4008                                         } else if (direction == LYX_DIR_RIGHT_TO_LEFT)
4009                                                 tmpx = paperwidth - LeftMargin(row_ptr) - 
4010                                                         font.stringWidth(tmpstring);
4011                                         pain.text(int(tmpx),
4012                                                   offset + row_ptr->baseline
4013                                                   - row_ptr->ascent_of_text
4014                                                   - maxdesc,
4015                                                   tmpstring, font);
4016                                 }
4017                         }
4018                 }
4019                 if (layout.labeltype == LABEL_BIBLIO && row_ptr->par->bibkey) {
4020                         font = GetFont(row_ptr->par, -1);
4021                         if (direction == LYX_DIR_LEFT_TO_RIGHT)
4022                                 tmpx = x - font.stringWidth(layout.labelsep)
4023                                         - row_ptr->par->bibkey->width(owner_->painter(), font);
4024                         else
4025                                 tmpx = paperwidth - LeftMargin(row_ptr)
4026                                         + font.stringWidth(layout.labelsep);
4027                         row_ptr->par->bibkey->draw(owner_->painter(),
4028                                                    font,
4029                                                    offset + row_ptr->baseline, 
4030                                                    tmpx);
4031                 }
4032         }
4033         
4034         /* is it a last row? */
4035         par = row_ptr->par->LastPhysicalPar();
4036         if (row_ptr->par->ParFromPos(RowLast(row_ptr) + 1) == par
4037             && (!row_ptr->next || row_ptr->next->par != row_ptr->par)) {     
4038                 
4039                 /* think about the margins */ 
4040                 if (!row_ptr->next)
4041                         y_bottom -= LYX_PAPER_MARGIN;
4042                 
4043                 /* draw a bottom pagebreak */ 
4044                 if (firstpar->pagebreak_bottom) {
4045 #if 0
4046                         pain.line(0, offset + y_bottom - 2 * DefaultHeight(),
4047                                   paperwidth,
4048                                   offset + y_bottom - 2 * DefaultHeight(),
4049                                   LColor::pagebreak, Painter::line_onoffdash);
4050 #else
4051                         LyXFont pb_font;
4052                         pb_font.setColor(LColor::pagebreak).decSize();
4053                         int w = 0, a = 0, d = 0;
4054                         pain.line(0,
4055                                   offset + y_bottom - 2 * DefaultHeight(), 
4056                                   paperwidth, 
4057                                   offset + y_bottom - 2 * DefaultHeight(),
4058                                   LColor::pagebreak,
4059                                   Painter::line_onoffdash)
4060                                 .rectText(0,
4061                                           0,
4062                                           _("Page Break (bottom)"),
4063                                           pb_font,
4064                                           LColor::background,
4065                                           LColor::background, false, w, a, d);
4066                         pain.rectText((paperwidth - w)/2,
4067                                       offset +y_top + 2*DefaultHeight() +d,
4068                                       _("Page Break (bottom)"),
4069                                       pb_font,
4070                                       LColor::background,
4071                                       LColor::background);
4072 #endif
4073                         y_bottom -= 3 * DefaultHeight();
4074                 }
4075                 
4076                 if (firstpar->added_space_bottom.kind() == VSpace::VFILL) {
4077                         /* draw a vfill bottom  */
4078                         pain.line(0, offset + y_bottom - 3 * DefaultHeight(),
4079                                   LYX_PAPER_MARGIN,
4080                                   offset + y_bottom - 3 * DefaultHeight(),
4081                                   LColor::vfillline);
4082                         pain.line(0, offset + y_bottom - 2,
4083                                   LYX_PAPER_MARGIN,
4084                                   offset + y_bottom - 2,
4085                                   LColor::vfillline);
4086                         pain.line(LYX_PAPER_MARGIN / 2,
4087                                   offset + y_bottom - 3 * DefaultHeight(),
4088                                   LYX_PAPER_MARGIN / 2,
4089                                   offset + y_bottom - 2,
4090                                   LColor::vfillline);
4091                         y_bottom -= 3* DefaultHeight();
4092                 }
4093                 
4094                 /* think about user added space */ 
4095                 y_bottom -= int(firstpar->added_space_bottom.inPixels(owner_));
4096                 
4097                 if (firstpar->line_bottom) {
4098                         /* draw a bottom line */
4099                         y_bottom -= GetFont(par, par->Last() - 1).ascent('x');
4100                         pain.line(0, offset + y_bottom,
4101                                   paperwidth, offset + y_bottom,
4102                                   LColor::topline, Painter::line_solid,
4103                                   Painter::line_thick);
4104                         y_bottom -= GetFont(par, par->Last() - 1).ascent('x');
4105                 }
4106
4107                 // draw an endlabel
4108                 int endlabel = row_ptr->par->GetEndLabel();
4109                 if (endlabel == END_LABEL_BOX ||
4110                     endlabel == END_LABEL_FILLED_BOX) {
4111                         LyXFont font = GetFont(row_ptr->par, RowLast(row_ptr));
4112                         int size = int(0.75*font.maxAscent());
4113                         int y = (offset + row_ptr->baseline) - size;
4114                         int x = (direction == LYX_DIR_LEFT_TO_RIGHT)
4115                                 ? paperwidth - LYX_PAPER_MARGIN - size
4116                                 : LYX_PAPER_MARGIN;
4117                         if (row_ptr->par->footnoteflag == LyXParagraph::OPEN_FOOTNOTE)
4118                                 if (direction == LYX_DIR_LEFT_TO_RIGHT)
4119                                         x -= LYX_PAPER_MARGIN/2;
4120                                 else {
4121                                         LyXFont font(LyXFont::ALL_SANE);
4122                                         font.setSize(LyXFont::SIZE_SMALL);
4123                                         x += font.textWidth("Mwide-figM", 10);
4124                                 }
4125                         if (row_ptr->fill <= size)
4126                                 x += (size - row_ptr->fill + 1) * direction;
4127                         if (endlabel == END_LABEL_BOX) {
4128                                 pain.line(x, y, x, y + size,
4129                                           LColor::eolmarker);
4130                                 pain.line(x + size, y, x + size , y + size,
4131                                           LColor::eolmarker);
4132                                 pain.line(x, y, x + size, y,
4133                                           LColor::eolmarker);
4134                                 pain.line(x, y + size, x + size, y + size,
4135                                           LColor::eolmarker);
4136                         } else
4137                                 pain.fillRectangle(x, y, size, size,
4138                                                    LColor::eolmarker);
4139                 }
4140         }
4141         
4142         /* draw the text in the pixmap */  
4143         pos_end = RowLast(row_ptr);
4144         
4145         vpos = row_ptr->pos;
4146         /* table stuff -- begin*/
4147         if (row_ptr->par->table) {
4148                 bool on_off;
4149                 int cell = NumberOfCell(row_ptr->par, row_ptr->pos);
4150                 float x_old = x;
4151                 x += row_ptr->par->table->GetBeginningOfTextInCell(cell);
4152                 
4153                 while (vpos <= pos_end)  {
4154                         pos = vis2log(vpos);
4155                         if (row_ptr->par->IsNewline(pos)) {
4156                                 
4157                                 x = x_old + row_ptr->par->table->WidthOfColumn(cell);
4158                                 /* draw the table lines, still very simple */
4159                                 on_off = !row_ptr->par->table->TopLine(cell);
4160                                 if ((!on_off ||
4161                                      !row_ptr->par->table->TopAlreadyDrawed(cell)) &&
4162                                     !row_ptr->par->table->IsContRow(cell))
4163                                         pain.line(int(x_old),
4164                                                   offset + row_ptr->baseline - row_ptr->ascent_of_text,
4165                                                   int(x),
4166                                                   offset + row_ptr->baseline - row_ptr->ascent_of_text,
4167                                                   LColor::tableline,
4168                                                   on_off ? Painter::line_onoffdash : Painter::line_solid);
4169                                 
4170                                 on_off = !row_ptr->par->table->BottomLine(cell);
4171                                 if ((!on_off && !row_ptr->par->table->RowHasContRow(cell)) ||
4172                                     row_ptr->par->table->VeryLastRow(cell))
4173                                         
4174                                         pain.line(int(x_old),
4175                                                   offset + y_bottom - 1,
4176                                                   int(x),
4177                                                   offset + y_bottom - 1,
4178                                                   LColor::tableline,
4179                                                   on_off ? Painter::line_onoffdash : Painter::line_solid);
4180                                 
4181                                 on_off = !row_ptr->par->table->LeftLine(cell);
4182                                 
4183                                 pain.line(int(x_old),
4184                                           offset + row_ptr->baseline - row_ptr->ascent_of_text,
4185                                           int(x_old),
4186                                           offset + y_bottom - 1,
4187                                           LColor::tableline,
4188                                           on_off ? Painter::line_onoffdash : Painter::line_solid);
4189                                 
4190                                 on_off = !row_ptr->par->table->RightLine(cell);
4191                                 
4192                                 pain.line(int(x) - row_ptr->par->table->AdditionalWidth(cell),
4193                                           offset + row_ptr->baseline - row_ptr->ascent_of_text,
4194                                           int(x) - row_ptr->par->table->AdditionalWidth(cell),
4195                                           offset + y_bottom - 1,
4196                                           LColor::tableline,
4197                                           on_off ? Painter::line_onoffdash : Painter::line_solid);
4198                                 
4199                                 x_old = x;
4200                                 /* take care about the alignment and other spaces */
4201                                 ++cell;
4202                                 x += row_ptr->par->table->GetBeginningOfTextInCell(cell);
4203                                 if (row_ptr->par->table->IsFirstCell(cell))
4204                                         --cell; // little hack, sorry
4205                                 ++vpos;
4206                         } else if (row_ptr->par->IsHfill(pos)) {
4207                                 x += 1;
4208                                 
4209                                 pain.line(int(x),
4210                                           offset + row_ptr->baseline - DefaultHeight() / 2,
4211                                           int(x),
4212                                           offset + row_ptr->baseline,
4213                                           LColor::vfillline);
4214                                 
4215                                 x += 2;
4216                                 ++vpos;
4217                         } else if (row_ptr->par->IsSeparator(pos)) {
4218                                 tmpx = x;
4219                                 x+= SingleWidth(row_ptr->par, pos);
4220 #warning Think about this.
4221 #if 0
4222                                 /* -------> Only draw protected spaces when
4223                                  * not in free-spacing mode. */
4224                                 if (row_ptr->par->GetChar(pos) == LyXParagraph::META_PROTECTED_SEPARATOR && !layout.free_spacing) {
4225                                         pain.line(int(tmpx),
4226                                                   offset + row_ptr->baseline - 3,
4227                                                   int(tmpx),
4228                                                   offset + row_ptr->baseline - 1,
4229                                                   LColor::vfillline);
4230                                         
4231                                         pain.line(int(tmpx),
4232                                                   offset + row_ptr->baseline - 1,
4233                                                   int(x - 2),
4234                                                   offset + row_ptr->baseline - 1,
4235                                                   LColor::vfillline);
4236                                         
4237                                         pain.line(int(x - 2),
4238                                                   offset + row_ptr->baseline - 3,
4239                                                   int(x - 2),
4240                                                   offset + row_ptr->baseline - 1,
4241                                                   LColor::vfillline);
4242                                         
4243                                         /* what about underbars? */
4244                                         font = GetFont(row_ptr->par, pos); 
4245                                         if (font.underbar() == LyXFont::ON
4246                                             && font.latex() != LyXFont::ON) {
4247                                                 pain.line(int(tmpx),
4248                                                           offset + row_ptr->baseline + 2,
4249                                                           int(x - tmpx),
4250                                                           offset + row_ptr->baseline + 2);
4251                                         }
4252                                 }
4253 #endif
4254                                 ++vpos;
4255                         } else
4256                                 draw(row_ptr, vpos, offset, x);
4257                 }
4258                 
4259                 /* do not forget the very last cell. This has no NEWLINE so 
4260                  * ignored by the code above*/ 
4261                 if (cell == row_ptr->par->table->GetNumberOfCells()-1){
4262                         x = x_old + row_ptr->par->table->WidthOfColumn(cell);
4263                         on_off = !row_ptr->par->table->TopLine(cell);
4264                         if ((!on_off ||
4265                              !row_ptr->par->table->TopAlreadyDrawed(cell)) &&
4266                             !row_ptr->par->table->IsContRow(cell))
4267                                 
4268                                 pain.line(int(x_old),
4269                                           offset + row_ptr->baseline - row_ptr->ascent_of_text,
4270                                           int(x),
4271                                           offset + row_ptr->baseline - row_ptr->ascent_of_text,
4272                                           LColor::tableline,
4273                                           on_off ? Painter::line_onoffdash : Painter::line_solid);
4274                         on_off = !row_ptr->par->table->BottomLine(cell);
4275                         if ((!on_off && !row_ptr->par->table->RowHasContRow(cell)) ||
4276                             row_ptr->par->table->VeryLastRow(cell))
4277                                 
4278                                 pain.line(int(x_old),
4279                                           offset + y_bottom - 1,
4280                                           int(x),
4281                                           offset + y_bottom - 1,
4282                                           LColor::tableline,
4283                                           on_off ? Painter::line_onoffdash : Painter::line_solid);
4284                         
4285                         on_off = !row_ptr->par->table->LeftLine(cell);
4286                         
4287                         pain.line(int(x_old),
4288                                   offset + row_ptr->baseline - row_ptr->ascent_of_text,
4289                                   int(x_old),
4290                                   offset + y_bottom - 1,
4291                                   LColor::tableline,
4292                                   on_off ? Painter::line_onoffdash : Painter::line_solid);
4293                         
4294                         on_off = !row_ptr->par->table->RightLine(cell);
4295                         
4296                         pain.line(int(x) - row_ptr->par->table->AdditionalWidth(cell),
4297                                   offset + row_ptr->baseline - row_ptr->ascent_of_text,
4298                                   int(x) - row_ptr->par->table->AdditionalWidth(cell),
4299                                   offset + y_bottom - 1,
4300                                   LColor::tableline,
4301                                   on_off ? Painter::line_onoffdash : Painter::line_solid);
4302                 }
4303         } else {
4304                 /* table stuff -- end*/
4305                 LyXParagraph::size_type main_body = 
4306                         BeginningOfMainBody(row_ptr->par);
4307                 if (main_body > 0 &&
4308                     (main_body-1 > pos_end || 
4309                      !row_ptr->par->IsLineSeparator(main_body-1)))
4310                         main_body = 0;
4311                 
4312                 while (vpos <= pos_end)  {
4313                         pos = vis2log(vpos);
4314                         if (main_body > 0 && pos == main_body-1) {
4315                                 x += fill_label_hfill
4316                                         + GetFont(row_ptr->par, -2).stringWidth(layout.labelsep)
4317                                         - SingleWidth(row_ptr->par, main_body-1);
4318                         }
4319                         
4320                         if (row_ptr->par->IsHfill(pos)) {
4321                                 x += 1;
4322                                 pain.line(int(x),
4323                                           offset + row_ptr->baseline - DefaultHeight() / 2,
4324                                           int(x),
4325                                           offset + row_ptr->baseline,
4326                                           LColor::vfillline);
4327                                 
4328                                 if (HfillExpansion(row_ptr, pos)) {
4329                                         if (pos >= main_body) {
4330                                                 pain.line(int(x),
4331                                                           offset + row_ptr->baseline - DefaultHeight() / 4,
4332                                                           int(x + fill_hfill),
4333                                                           offset + row_ptr->baseline - DefaultHeight() / 4,
4334                                                           LColor::vfillline,
4335                                                           Painter::line_onoffdash);
4336                                                 x += fill_hfill;
4337                                         } else {
4338                                                 pain.line(int(x),
4339                                                           offset + row_ptr->baseline - DefaultHeight() / 4,
4340                                                           int(x + fill_label_hfill),
4341                                                           offset + row_ptr->baseline - DefaultHeight() / 4,
4342                                                           LColor::vfillline,
4343                                                           Painter::line_onoffdash);
4344                                                 
4345                                                 x += fill_label_hfill;
4346                                         }
4347                                         pain.line(int(x),
4348                                                   offset + row_ptr->baseline - DefaultHeight() / 2,
4349                                                   int(x),
4350                                                   offset + row_ptr->baseline,
4351                                                   LColor::vfillline);
4352                                 }
4353                                 x += 2;
4354                                 ++vpos;
4355                         } else if (row_ptr->par->IsSeparator(pos)) {
4356                                 tmpx = x;
4357                                 x+= SingleWidth(row_ptr->par, pos);
4358                                 if (pos >= main_body)
4359                                         x+= fill_separator;
4360 #warning Think about this
4361 #if 0
4362                                 /* -------> Only draw protected spaces when
4363                                  * not in free-spacing mode. */
4364                                 if (row_ptr->par->GetChar(pos) == LyXParagraph::META_PROTECTED_SEPARATOR && !layout.free_spacing) {
4365                                         
4366                                         pain.line(int(tmpx),
4367                                                   offset + row_ptr->baseline - 3,
4368                                                   int(tmpx),
4369                                                   offset + row_ptr->baseline - 1,
4370                                                   LColor::vfillline);
4371                                         
4372                                         pain.line(int(tmpx),
4373                                                   offset + row_ptr->baseline - 1,
4374                                                   int(x - 2),
4375                                                   offset + row_ptr->baseline - 1,
4376                                                   LColor::vfillline);
4377                                         
4378                                         pain.line(int(x - 2),
4379                                                   offset + row_ptr->baseline - 3,
4380                                                   int(x - 2),
4381                                                   offset + row_ptr->baseline - 1,
4382                                                   LColor::vfillline);
4383                                         
4384                                         /* what about underbars? */
4385                                         font = GetFont(row_ptr->par, pos); 
4386                                         if (font.underbar() == LyXFont::ON
4387                                             && font.latex() != LyXFont::ON) {
4388                                                 pain.line(int(tmpx),
4389                                                           offset + row_ptr->baseline + 2,
4390                                                           int(x - tmpx),
4391                                                           offset + row_ptr->baseline + 2);
4392                                         }
4393                                 }
4394 #endif
4395                                 ++vpos;
4396                         } else
4397                                 draw(row_ptr, vpos, offset, x);
4398                 }
4399         }
4400 }
4401
4402
4403 int LyXText::DefaultHeight() const
4404 {
4405         LyXFont font(LyXFont::ALL_SANE);
4406         return int(font.maxAscent() + font.maxDescent() * 1.5);
4407 }
4408
4409    
4410 /* returns the column near the specified x-coordinate of the row 
4411 * x is set to the real beginning of this column  */ 
4412 int LyXText::GetColumnNearX(Row * row, int & x) const
4413 {
4414         float tmpx = 0.0;
4415         float fill_separator, fill_hfill, fill_label_hfill;
4416    
4417         PrepareToPrint(row, tmpx, fill_separator,
4418                        fill_hfill, fill_label_hfill);
4419
4420         LyXDirection direction = row->par->getParDirection();
4421         LyXParagraph::size_type vc = row->pos;
4422         LyXParagraph::size_type last = RowLast(row);
4423         LyXParagraph::size_type c = 0;
4424
4425         LyXLayout const & layout = textclasslist.Style(parameters->textclass,
4426                                                        row->par->GetLayout());
4427         /* table stuff -- begin */
4428         if (row->par->table) {
4429                 if (row->next && row->next->par == row->par //the last row doesn't need a newline at the end
4430                     && row->par->IsNewline(last))
4431                         last--;
4432                 int cell = NumberOfCell(row->par, row->pos);
4433                 float x_old = tmpx;
4434                 bool ready = false;
4435                 tmpx += row->par->table->GetBeginningOfTextInCell(cell);
4436                 while (vc <= last
4437                        && (c = vis2log(vc)) >= 0
4438                        && tmpx + (SingleWidth(row->par, c)/2) <= x
4439                        && !ready){
4440                         if (row->par->IsNewline(c)) {
4441                                 if (x_old + row->par->table->WidthOfColumn(cell) <= x){
4442                                         tmpx = x_old + row->par->table->WidthOfColumn(cell);
4443                                         x_old = tmpx;
4444                                         ++cell;
4445                                         tmpx += row->par->table->GetBeginningOfTextInCell(cell);
4446                                         ++vc;
4447                                 } else
4448                                         ready = true;
4449                         } else {
4450                                 tmpx += SingleWidth(row->par, c);
4451                                 ++vc;
4452                         }
4453                 }
4454         } else {
4455                 /* table stuff -- end*/
4456                 LyXParagraph::size_type main_body = BeginningOfMainBody(row->par);
4457                 float last_tmpx = tmpx;
4458
4459                 if (main_body > 0 &&
4460                     (main_body-1 > last || 
4461                      !row->par->IsLineSeparator(main_body-1)))
4462                         main_body = 0;
4463
4464                 while (vc <= last && tmpx <= x) {
4465                         c = vis2log(vc);
4466                         last_tmpx = tmpx;
4467                         if (main_body > 0 && c == main_body-1) {
4468                                 tmpx += fill_label_hfill +
4469                                         GetFont(row->par, -2).stringWidth(layout.labelsep);
4470                                 if (row->par->IsLineSeparator(main_body-1))
4471                                         tmpx -= SingleWidth(row->par, main_body-1);
4472                         }
4473              
4474                         tmpx += SingleWidth(row->par, c);
4475                         if (HfillExpansion(row, c)) {
4476                                 if (c >= main_body)
4477                                         tmpx += fill_hfill;
4478                                 else
4479                                         tmpx += fill_label_hfill;
4480                         }
4481                         else if (c >= main_body
4482                                  && row->par->IsSeparator(c)) {
4483                                 tmpx+= fill_separator;  
4484                         }
4485                         ++vc;
4486                 }
4487
4488                 if (vc > row->pos && (tmpx+last_tmpx)/2 > x) {
4489                         vc--;
4490                         tmpx = last_tmpx;
4491                 }
4492         }
4493         /* make sure that a last space in a row doesnt count */
4494         if (row->pos <= last
4495             && !(!row->next || row->next->par != row->par))
4496                 if (direction == LYX_DIR_LEFT_TO_RIGHT && vc > last
4497                     && row->par->IsLineSeparator(vis2log(last)) ) {
4498                         vc = last;
4499                         tmpx -= fill_separator+SingleWidth(row->par, vis2log(last));
4500                 } else if (direction == LYX_DIR_RIGHT_TO_LEFT 
4501                            && vc == row->pos
4502                            && row->par->IsLineSeparator(vis2log(row->pos)) ) {
4503                         vc = row->pos+1;
4504                         tmpx += fill_separator+SingleWidth(row->par, vis2log(row->pos));
4505                 }
4506         if (row->pos > last)  // Row is empty?
4507                 c = row->pos;
4508         else if (vc > last ||
4509                  (row->par->table && vc > row->pos && row->par->IsNewline(vc)) ){
4510                 int pos = (vc > last+1) ? last : vc - 1; 
4511                 c = vis2log(pos);
4512                 if (row->par->getLetterDirection(c) == LYX_DIR_LEFT_TO_RIGHT)
4513                         ++c;
4514         } else {
4515                 c = vis2log(vc);
4516                 LyXDirection direction = row->par->getLetterDirection(c);
4517                 if (vc > row->pos && row->par->IsLineSeparator(c)
4518                     && row->par->getLetterDirection(vis2log(vc - 1)) != direction)
4519                         c = vis2log(vc-1);
4520                 if (direction == LYX_DIR_RIGHT_TO_LEFT)
4521                         ++c;
4522         }
4523
4524         if (!row->par->table && row->pos <= last && c > last
4525             && row->par->IsNewline(last)) {
4526                 if (row->par->getLetterDirection(last) == LYX_DIR_LEFT_TO_RIGHT)
4527                         tmpx -= SingleWidth(row->par, last);
4528                 else
4529                         tmpx += SingleWidth(row->par, last);
4530                 c = last;
4531         }
4532
4533         c -= row->pos;
4534         x = int(tmpx);
4535         return c;
4536 }
4537
4538    
4539 /* turn the selection into a new environment. If there is no selection,
4540 * create an empty environment */ 
4541 void LyXText::InsertFootnoteEnvironment(LyXParagraph::footnote_kind kind)
4542 {
4543    /* no footnoteenvironment in a footnoteenvironment */ 
4544    if (cursor.par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
4545       WriteAlert(_("Impossible operation"), 
4546                  _("You can't insert a float in a float!"), 
4547                  _("Sorry."));
4548      return;
4549    }
4550    /* no marginpars in minipages */
4551    if (kind == LyXParagraph::MARGIN 
4552       && cursor.par->pextra_type == LyXParagraph::PEXTRA_MINIPAGE) {
4553       WriteAlert(_("Impossible operation"), 
4554                  _("You can't insert a marginpar in a minipage!"), 
4555                  _("Sorry."));
4556       return;
4557    }
4558    
4559    /* this doesnt make sense, if there is no selection */ 
4560    bool dummy_selection = false;
4561    if (!selection) {
4562       sel_start_cursor = cursor;       /* dummy selection  */
4563       sel_end_cursor = cursor;
4564       dummy_selection = true;
4565    }
4566    
4567    LyXParagraph *tmppar;
4568
4569    if (sel_start_cursor.par->table || sel_end_cursor.par->table){
4570       WriteAlert(_("Impossible operation"), _("Cannot cut table."), _("Sorry."));
4571       return;
4572    }
4573      
4574    /* a test to make sure there is not already a footnote
4575     * in the selection. */
4576    
4577    tmppar = sel_start_cursor.par->ParFromPos(sel_start_cursor.pos);
4578    
4579    while (tmppar != sel_end_cursor.par->ParFromPos(sel_end_cursor.pos) && 
4580           tmppar->footnoteflag == LyXParagraph::NO_FOOTNOTE)
4581      tmppar = tmppar->next;
4582    
4583    if (tmppar != sel_end_cursor.par->ParFromPos(sel_end_cursor.pos)
4584        || tmppar->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
4585       WriteAlert(_("Impossible operation"), 
4586                  _("Float would include float!"), 
4587                  _("Sorry."));
4588       return;
4589    }
4590    
4591    /* ok we have a selection. This is always between sel_start_cursor
4592     * and sel_end cursor */
4593
4594    SetUndo(Undo::FINISH, 
4595            sel_start_cursor.par->ParFromPos(sel_start_cursor.pos)->previous, 
4596            sel_end_cursor.par->ParFromPos(sel_end_cursor.pos)->next); 
4597    
4598    if (sel_end_cursor.pos > 0 
4599        && sel_end_cursor.par->IsLineSeparator(sel_end_cursor.pos - 1))
4600      sel_end_cursor.pos--;             /* please break before a space at
4601                                         * the end */
4602    if (sel_start_cursor.par == sel_end_cursor.par
4603        && sel_start_cursor.pos > sel_end_cursor.pos)
4604      sel_start_cursor.pos--;
4605
4606    sel_end_cursor.par->BreakParagraphConservative(sel_end_cursor.pos);
4607    
4608    sel_end_cursor.par = sel_end_cursor.par->Next();
4609    sel_end_cursor.pos = 0;
4610    
4611    // don't forget to insert a dummy layout paragraph if necessary
4612    if (sel_start_cursor.par->GetLayout() != sel_end_cursor.par->layout){
4613      sel_end_cursor.par->BreakParagraphConservative(0);
4614      sel_end_cursor.par->layout = LYX_DUMMY_LAYOUT;
4615      sel_end_cursor.par = sel_end_cursor.par->next;
4616    }
4617    else
4618      sel_end_cursor.par->layout = LYX_DUMMY_LAYOUT;
4619
4620    cursor = sel_end_cursor;
4621
4622    /* please break behind a space, if there is one. The space should
4623     * be erased too */ 
4624    if (sel_start_cursor.pos > 0 
4625        && sel_start_cursor.par->IsLineSeparator(sel_start_cursor.pos - 1))
4626      sel_start_cursor.pos--;
4627    if (sel_start_cursor.par->IsLineSeparator(sel_start_cursor.pos)) {
4628       sel_start_cursor.par->Erase(sel_start_cursor.pos);
4629    }
4630    
4631    sel_start_cursor.par->BreakParagraphConservative(sel_start_cursor.pos);
4632    tmppar = sel_start_cursor.par->Next();
4633    
4634    if (dummy_selection) {
4635            tmppar->Clear();
4636            if (kind == LyXParagraph::TAB
4637                || kind == LyXParagraph::FIG 
4638                || kind == LyXParagraph::WIDE_TAB
4639                || kind == LyXParagraph::WIDE_FIG 
4640                || kind == LyXParagraph::ALGORITHM) {
4641                    pair<bool, LyXTextClass::size_type> lres =
4642                            textclasslist.NumberOfLayout(parameters->textclass,
4643                                                         "Caption");
4644                    LyXTextClass::size_type lay;
4645                    if (lres.first) {
4646                            // layout fount
4647                            lay = lres.second;
4648                    } else {
4649                            // layout not found
4650                            lay = 0; // use default layout "Standard" (0)
4651                    }
4652                    tmppar->SetLayout(lay);
4653            }
4654    }
4655    else {
4656      if (sel_start_cursor.pos > 0) {
4657        /* the footnote-environment should begin with a standard layout.
4658         * Imagine you insert a footnote within an enumeration, you 
4659         * certainly do not want an enumerated footnote! */ 
4660        tmppar->Clear();
4661      }
4662      else {
4663        /* this is a exception the user would sometimes expect, I hope */
4664        sel_start_cursor.par->Clear();
4665      }
4666    }
4667    
4668    while (tmppar != sel_end_cursor.par) {
4669       tmppar->footnoteflag = LyXParagraph::OPEN_FOOTNOTE;
4670       tmppar->footnotekind = kind;
4671       tmppar = tmppar->Next();
4672    } 
4673
4674    RedoParagraphs(sel_start_cursor, sel_end_cursor.par->Next());
4675    
4676    SetCursor(sel_start_cursor.par->Next(), 0);
4677
4678    ClearSelection();
4679 }
4680    
4681
4682 // returns pointer to a specified row
4683 Row * LyXText::GetRow(LyXParagraph * par,
4684                       LyXParagraph::size_type pos, long & y) const
4685 {
4686         Row * tmprow;
4687
4688         if (currentrow) {
4689                 if (par == currentrow->par
4690                     || par == currentrow->par->Previous()) {
4691                         // do not dereference par, it may have been deleted
4692                         // already! (Matthias)
4693
4694                         // Walk backwards as long as the previous
4695                         // rows par is not par
4696                         while (currentrow->previous
4697                                && currentrow->previous->par != par) {
4698                                 currentrow = currentrow->previous;
4699                                 currentrow_y -= currentrow->height;
4700                         }
4701                         // Walk backwards as long as the previous
4702                         // rows par _is_ par
4703                         while (currentrow->previous
4704                                && currentrow->previous->par == par) {
4705                                 currentrow = currentrow->previous;
4706                                 currentrow_y -= currentrow->height;
4707                         }
4708                 }
4709
4710                 tmprow = currentrow;
4711                 y = currentrow_y;
4712                 // find the first row of the specified paragraph
4713                 while (tmprow->next
4714                        && tmprow->par != par) {
4715                         y += tmprow->height;
4716                         tmprow = tmprow->next;
4717                 }
4718                 
4719                 if (tmprow->par == par){
4720                         // now find the wanted row
4721                         while (tmprow->pos < pos
4722                                && tmprow->next
4723                                && tmprow->next->par == par
4724                                && tmprow->next->pos <= pos) {
4725                                 y += tmprow->height;
4726                                 tmprow = tmprow->next;
4727                         }
4728                         currentrow = tmprow;
4729                         currentrow_y = y;
4730                         return tmprow;
4731                 }
4732         }
4733
4734         tmprow = firstrow;
4735         y = 0;
4736         // find the first row of the specified paragraph
4737         while (tmprow->next && tmprow->par != par) {
4738                 y += tmprow->height;
4739                 tmprow = tmprow->next;
4740         }
4741         
4742         // now find the wanted row
4743         while (tmprow->pos < pos
4744                && tmprow->next
4745                && tmprow->next->par == par
4746                && tmprow->next->pos <= pos) {
4747                 y += tmprow->height;
4748                 tmprow = tmprow->next;
4749         }
4750         
4751         currentrow = tmprow;
4752         currentrow_y = y;
4753         
4754         return tmprow;
4755 }