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