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