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