]> git.lyx.org Git - lyx.git/blob - src/text.C
"Main body" is now just "body"
[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-2001 The LyX Team.
8  *
9  * ====================================================== */
10
11 #include <config.h>
12
13 #include "lyxtext.h"
14 #include "lyxrow.h"
15 #include "paragraph.h"
16 #include "gettext.h"
17 #include "bufferparams.h"
18 #include "buffer.h"
19 #include "debug.h"
20 #include "intl.h"
21 #include "lyxrc.h"
22 #include "encoding.h"
23 #include "frontends/LyXView.h"
24 #include "frontends/Painter.h"
25 #include "frontends/font_metrics.h"
26 #include "frontends/screen.h"
27 #include "frontends/WorkArea.h"
28 #include "bufferview_funcs.h"
29 #include "BufferView.h"
30 #include "language.h"
31 #include "ParagraphParameters.h"
32 #include "undo_funcs.h"
33 #include "WordLangTuple.h"
34 #include "paragraph_funcs.h"
35 #include "rowpainter.h"
36
37 #include "insets/insettext.h"
38
39 #include "support/textutils.h"
40 #include "support/LAssert.h"
41 #include "support/lstrings.h"
42
43 #include <algorithm>
44
45 using std::max;
46 using std::min;
47 using std::endl;
48 using std::pair;
49 using lyx::pos_type;
50
51 /// top, right, bottom pixel margin
52 extern int const PAPER_MARGIN = 20;
53 /// margin for changebar
54 extern int const CHANGEBAR_MARGIN = 10;
55 /// left margin
56 extern int const LEFT_MARGIN = PAPER_MARGIN + CHANGEBAR_MARGIN;
57
58 extern int bibitemMaxWidth(BufferView *, LyXFont const &);
59
60
61 int LyXText::top_y() const
62 {
63         if (!top_row_)
64                 return 0;
65         
66         int y = 0;
67         for (Row * row = firstrow; row && row != top_row_; row = row->next()) {
68                 y += row->height();
69         }
70         return y + top_row_offset_;
71 }
72
73
74 void LyXText::top_y(int newy)
75 {
76         if (!firstrow)
77                 return;
78         lyxerr[Debug::GUI] << "setting top y = " << newy << endl;
79         
80         int y = newy;
81         top_row_ = getRowNearY(y);
82         top_row_offset_ = newy - y;
83         lyxerr[Debug::GUI] << "changing reference to row: " << top_row_
84                << " offset: " << top_row_offset_ << endl;
85 }
86
87
88 int LyXText::workWidth(BufferView & bview) const
89 {
90         if (inset_owner) {
91                 // FIXME: pass (const ?) ref
92                 return inset_owner->textWidth(&bview);
93         }
94         return bview.workWidth();
95 }
96
97
98 int LyXText::workWidth(BufferView & bview, Inset * inset) const
99 {
100         Paragraph * par = inset->parOwner();
101         lyx::Assert(par);
102
103         pos_type pos = par->getPositionOfInset(inset);
104         lyx::Assert(pos != -1);
105
106         LyXLayout_ptr const & layout = par->layout();
107
108         if (layout->margintype != MARGIN_RIGHT_ADDRESS_BOX) {
109                 // Optimization here: in most cases, the real row is
110                 // not needed, but only the par/pos values. So we just
111                 // construct a dummy row for leftMargin. (JMarc)
112                 Row dummyrow;
113                 dummyrow.par(par);
114                 dummyrow.pos(pos);
115                 return workWidth(bview) - leftMargin(&bview, &dummyrow);
116         } else {
117                 int dummy_y;
118                 Row * row = getRow(par, pos, dummy_y);
119                 Row * frow = row;
120                 while (frow->previous() && frow->par() == frow->previous()->par())
121                         frow = frow->previous();
122
123                 // FIXME: I don't understand this code - jbl
124
125                 unsigned int maxw = 0;
126                 while (!frow->isParEnd()) {
127                         if ((frow != row) && (maxw < frow->width()))
128                                 maxw = frow->width();
129                         frow = frow->next();
130                 }
131                 if (maxw)
132                         return maxw;
133
134         }
135         return workWidth(bview);
136 }
137
138
139 int LyXText::getRealCursorX(BufferView * bview) const
140 {
141         int x = cursor.x();
142         if (the_locking_inset && (the_locking_inset->getLyXText(bview)!=this))
143                 x = the_locking_inset->getLyXText(bview)->getRealCursorX(bview);
144         return x;
145 }
146
147
148 unsigned char LyXText::transformChar(unsigned char c, Paragraph * par,
149                         pos_type pos) const
150 {
151         if (!Encodings::is_arabic(c))
152                 if (lyxrc.font_norm_type == LyXRC::ISO_8859_6_8 && IsDigit(c))
153                         return c + (0xb0 - '0');
154                 else
155                         return c;
156
157         unsigned char const prev_char = pos > 0 ? par->getChar(pos-1) : ' ';
158         unsigned char next_char = ' ';
159
160         for (pos_type i = pos+1; i < par->size(); ++i)
161                 if (!Encodings::IsComposeChar_arabic(par->getChar(i))) {
162                         next_char = par->getChar(i);
163                         break;
164                 }
165
166         if (Encodings::is_arabic(next_char)) {
167                 if (Encodings::is_arabic(prev_char) &&
168                         !Encodings::is_arabic_special(prev_char))
169                         return Encodings::TransformChar(c, Encodings::FORM_MEDIAL);
170                 else
171                         return Encodings::TransformChar(c, Encodings::FORM_INITIAL);
172         } else {
173                 if (Encodings::is_arabic(prev_char) &&
174                         !Encodings::is_arabic_special(prev_char))
175                         return Encodings::TransformChar(c, Encodings::FORM_FINAL);
176                 else
177                         return Encodings::TransformChar(c, Encodings::FORM_ISOLATED);
178         }
179 }
180
181 // This is the comments that some of the warnings below refers to.
182 // There are some issues in this file and I don't think they are
183 // really related to the FIX_DOUBLE_SPACE patch. I'd rather think that
184 // this is a problem that has been here almost from day one and that a
185 // larger userbase with differenct access patters triggers the bad
186 // behaviour. (segfaults.) What I think happen is: In several places
187 // we store the paragraph in the current cursor and then moves the
188 // cursor. This movement of the cursor will delete paragraph at the
189 // old position if it is now empty. This will make the temporary
190 // pointer to the old cursor paragraph invalid and dangerous to use.
191 // And is some cases this will trigger a segfault. I have marked some
192 // of the cases where this happens with a warning, but I am sure there
193 // are others in this file and in text2.C. There is also a note in
194 // Delete() that you should read. In Delete I store the paragraph->id
195 // instead of a pointer to the paragraph. I am pretty sure this faulty
196 // use of temporary pointers to paragraphs that might have gotten
197 // invalidated (through a cursor movement) before they are used, are
198 // the cause of the strange crashes we get reported often.
199 //
200 // It is very tiresom to change this code, especially when it is as
201 // hard to read as it is. Help to fix all the cases where this is done
202 // would be greately appreciated.
203 //
204 // Lgb
205
206 int LyXText::singleWidth(BufferView * bview, Paragraph * par,
207                          pos_type pos) const
208 {
209         char const c = par->getChar(pos);
210         return singleWidth(bview, par, pos, c);
211 }
212
213
214 int LyXText::singleWidth(BufferView * bview, Paragraph * par,
215                          pos_type pos, char c) const
216 {
217         LyXFont const font = getFont(bview->buffer(), par, pos);
218
219         // The most common case is handled first (Asger)
220         if (IsPrintable(c)) {
221                 if (font.language()->RightToLeft()) {
222                         if (font.language()->lang() == "arabic" &&
223                             (lyxrc.font_norm_type == LyXRC::ISO_8859_6_8 ||
224                              lyxrc.font_norm_type == LyXRC::ISO_10646_1))
225                                 if (Encodings::IsComposeChar_arabic(c))
226                                         return 0;
227                                 else
228                                         c = transformChar(c, par, pos);
229                         else if (font.language()->lang() == "hebrew" &&
230                                  Encodings::IsComposeChar_hebrew(c))
231                                 return 0;
232                 }
233                 return font_metrics::width(c, font);
234
235         } else if (IsHfillChar(c)) {
236                 // Because of the representation as vertical lines
237                 return 3;
238         } else if (c == Paragraph::META_INSET) {
239                 Inset * tmpinset = par->getInset(pos);
240                 if (tmpinset) {
241 #if 1
242                         // this IS needed otherwise on initialitation we don't get the fill
243                         // of the row right (ONLY on initialization if we read a file!)
244                         // should be changed! (Jug 20011204)
245                         tmpinset->update(bview, font);
246 #endif
247                         return tmpinset->width(bview, font);
248                 } else
249                         return 0;
250
251         } else if (IsSeparatorChar(c))
252                 c = ' ';
253         else if (IsNewlineChar(c))
254                 c = 'n';
255         return font_metrics::width(c, font);
256 }
257
258
259 void LyXText::computeBidiTables(Buffer const * buf, Row * row) const
260 {
261         bidi_same_direction = true;
262         if (!lyxrc.rtl_support) {
263                 bidi_start = -1;
264                 return;
265         }
266
267         Inset * inset = row->par()->inInset();
268         if (inset && inset->owner() &&
269             inset->owner()->lyxCode() == Inset::ERT_CODE) {
270                 bidi_start = -1;
271                 return;
272         }
273
274         bidi_start = row->pos();
275         bidi_end = row->lastPrintablePos();
276
277         if (bidi_start > bidi_end) {
278                 bidi_start = -1;
279                 return;
280         }
281
282         if (bidi_end + 2 - bidi_start >
283             static_cast<pos_type>(log2vis_list.size())) {
284                 pos_type new_size =
285                         (bidi_end + 2 - bidi_start < 500) ?
286                         500 : 2 * (bidi_end + 2 - bidi_start);
287                 log2vis_list.resize(new_size);
288                 vis2log_list.resize(new_size);
289                 bidi_levels.resize(new_size);
290         }
291
292         vis2log_list[bidi_end + 1 - bidi_start] = -1;
293         log2vis_list[bidi_end + 1 - bidi_start] = -1;
294
295         pos_type stack[2];
296         bool const rtl_par =
297                 row->par()->isRightToLeftPar(buf->params);
298         int level = 0;
299         bool rtl = false;
300         bool rtl0 = false;
301         pos_type const body_pos = row->par()->beginningOfBody();
302
303         for (pos_type lpos = bidi_start; lpos <= bidi_end; ++lpos) {
304                 bool is_space = row->par()->isLineSeparator(lpos);
305                 pos_type const pos =
306                         (is_space && lpos + 1 <= bidi_end &&
307                          !row->par()->isLineSeparator(lpos + 1) &&
308                          !row->par()->isNewline(lpos + 1))
309                         ? lpos + 1 : lpos;
310                 LyXFont font = row->par()->getFontSettings(buf->params, pos);
311                 if (pos != lpos && 0 < lpos && rtl0 && font.isRightToLeft() &&
312                     font.number() == LyXFont::ON &&
313                     row->par()->getFontSettings(buf->params, lpos - 1).number()
314                     == LyXFont::ON) {
315                         font = row->par()->getFontSettings(buf->params, lpos);
316                         is_space = false;
317                 }
318
319
320                 bool new_rtl = font.isVisibleRightToLeft();
321                 bool new_rtl0 = font.isRightToLeft();
322                 int new_level;
323
324                 if (lpos == body_pos - 1
325                     && row->pos() < body_pos - 1
326                     && is_space) {
327                         new_level = (rtl_par) ? 1 : 0;
328                         new_rtl = new_rtl0 = rtl_par;
329                 } else if (new_rtl0)
330                         new_level = (new_rtl) ? 1 : 2;
331                 else
332                         new_level = (rtl_par) ? 2 : 0;
333
334                 if (is_space && new_level >= level) {
335                         new_level = level;
336                         new_rtl = rtl;
337                         new_rtl0 = rtl0;
338                 }
339
340                 int new_level2 = new_level;
341
342                 if (level == new_level && rtl0 != new_rtl0) {
343                         --new_level2;
344                         log2vis_list[lpos - bidi_start] = (rtl) ? 1 : -1;
345                 } else if (level < new_level) {
346                         log2vis_list[lpos - bidi_start] =  (rtl) ? -1 : 1;
347                         if (new_level > rtl_par)
348                                 bidi_same_direction = false;
349                 } else
350                         log2vis_list[lpos - bidi_start] = (new_rtl) ? -1 : 1;
351                 rtl = new_rtl;
352                 rtl0 = new_rtl0;
353                 bidi_levels[lpos - bidi_start] = new_level;
354
355                 while (level > new_level2) {
356                         pos_type old_lpos = stack[--level];
357                         int delta = lpos - old_lpos - 1;
358                         if (level % 2)
359                                 delta = -delta;
360                         log2vis_list[lpos - bidi_start] += delta;
361                         log2vis_list[old_lpos - bidi_start] += delta;
362                 }
363                 while (level < new_level)
364                         stack[level++] = lpos;
365         }
366
367         while (level > 0) {
368                 pos_type const old_lpos = stack[--level];
369                 int delta = bidi_end - old_lpos;
370                 if (level % 2)
371                         delta = -delta;
372                 log2vis_list[old_lpos - bidi_start] += delta;
373         }
374
375         pos_type vpos = bidi_start - 1;
376         for (pos_type lpos = bidi_start;
377              lpos <= bidi_end; ++lpos) {
378                 vpos += log2vis_list[lpos - bidi_start];
379                 vis2log_list[vpos - bidi_start] = lpos;
380                 log2vis_list[lpos - bidi_start] = vpos;
381         }
382 }
383
384
385 // This method requires a previous call to ComputeBidiTables()
386 bool LyXText::isBoundary(Buffer const * buf, Paragraph * par,
387                          pos_type pos) const
388 {
389         if (!lyxrc.rtl_support || pos == 0)
390                 return false;
391
392         if (!bidi_InRange(pos - 1)) {
393                 /// This can happen if pos is the first char of a row.
394                 /// Returning false in this case is incorrect!
395                 return false;
396         }
397
398         bool const rtl = bidi_level(pos - 1) % 2;
399         bool const rtl2 = bidi_InRange(pos)
400                 ? bidi_level(pos) % 2
401                 : par->isRightToLeftPar(buf->params);
402         return rtl != rtl2;
403 }
404
405
406 bool LyXText::isBoundary(Buffer const * buf, Paragraph * par,
407                          pos_type pos, LyXFont const & font) const
408 {
409         if (!lyxrc.rtl_support)
410                 return false;    // This is just for speedup
411
412         bool const rtl = font.isVisibleRightToLeft();
413         bool const rtl2 = bidi_InRange(pos)
414                 ? bidi_level(pos) % 2
415                 : par->isRightToLeftPar(buf->params);
416         return rtl != rtl2;
417 }
418
419
420 int LyXText::leftMargin(BufferView * bview, Row const * row) const
421 {
422         Inset * ins;
423         if ((row->par()->getChar(row->pos()) == Paragraph::META_INSET) &&
424                 (ins=row->par()->getInset(row->pos())) &&
425                 (ins->needFullRow() || ins->display()))
426                 return LEFT_MARGIN;
427
428         LyXTextClass const & tclass =
429                 bview->buffer()->params.getLyXTextClass();
430         LyXLayout_ptr const & layout = row->par()->layout();
431
432         string parindent = layout->parindent;
433
434         int x = LEFT_MARGIN;
435
436         x += font_metrics::signedWidth(tclass.leftmargin(), tclass.defaultfont());
437
438         // this is the way, LyX handles the LaTeX-Environments.
439         // I have had this idea very late, so it seems to be a
440         // later added hack and this is true
441         if (!row->par()->getDepth()) {
442                 if (row->par()->layout() == tclass.defaultLayout()) {
443                         // find the previous same level paragraph
444                         if (row->par()->previous()) {
445                                 Paragraph * newpar = row->par()
446                                         ->depthHook(row->par()->getDepth());
447                                 if (newpar &&
448                                     newpar->layout()->nextnoindent)
449                                         parindent.erase();
450                         }
451                 }
452         } else {
453                 // find the next level paragraph
454
455                 Paragraph * newpar = row->par()->outerHook();
456
457                 // make a corresponding row. Needed to call LeftMargin()
458
459                 // check wether it is a sufficent paragraph
460                 if (newpar && newpar->layout()->isEnvironment()) {
461                         Row dummyrow;
462                         dummyrow.par(newpar);
463                         dummyrow.pos(newpar->size());
464                         x = leftMargin(bview, &dummyrow);
465                 } else {
466                         // this is no longer an error, because this function
467                         // is used to clear impossible depths after changing
468                         // a layout. Since there is always a redo,
469                         // LeftMargin() is always called
470                         row->par()->params().depth(0);
471                 }
472
473                 if (newpar && row->par()->layout() == tclass.defaultLayout()) {
474                         if (newpar->params().noindent())
475                                 parindent.erase();
476                         else {
477                                 parindent = newpar->layout()->parindent;
478                         }
479
480                 }
481         }
482
483         LyXFont const labelfont = getLabelFont(bview->buffer(), row->par());
484         switch (layout->margintype) {
485         case MARGIN_DYNAMIC:
486                 if (!layout->leftmargin.empty()) {
487                         x += font_metrics::signedWidth(layout->leftmargin,
488                                                   tclass.defaultfont());
489                 }
490                 if (!row->par()->getLabelstring().empty()) {
491                         x += font_metrics::signedWidth(layout->labelindent,
492                                                   labelfont);
493                         x += font_metrics::width(row->par()->getLabelstring(),
494                                             labelfont);
495                         x += font_metrics::width(layout->labelsep, labelfont);
496                 }
497                 break;
498         case MARGIN_MANUAL:
499                 x += font_metrics::signedWidth(layout->labelindent, labelfont);
500                 // The width of an empty par, even with manual label, should be 0
501                 if (!row->par()->empty() && row->pos() >= row->par()->beginningOfBody()) {
502                         if (!row->par()->getLabelWidthString().empty()) {
503                                 x += font_metrics::width(row->par()->getLabelWidthString(),
504                                                labelfont);
505                                 x += font_metrics::width(layout->labelsep, labelfont);
506                         }
507                 }
508                 break;
509         case MARGIN_STATIC:
510                 x += font_metrics::signedWidth(layout->leftmargin, tclass.defaultfont()) * 4
511                         / (row->par()->getDepth() + 4);
512                 break;
513         case MARGIN_FIRST_DYNAMIC:
514                 if (layout->labeltype == LABEL_MANUAL) {
515                         if (row->pos() >= row->par()->beginningOfBody()) {
516                                 x += font_metrics::signedWidth(layout->leftmargin,
517                                                           labelfont);
518                         } else {
519                                 x += font_metrics::signedWidth(layout->labelindent,
520                                                           labelfont);
521                         }
522                 } else if (row->pos()
523                            // Special case to fix problems with
524                            // theorems (JMarc)
525                            || (layout->labeltype == LABEL_STATIC
526                                && layout->latextype == LATEX_ENVIRONMENT
527                                && ! row->par()->isFirstInSequence())) {
528                         x += font_metrics::signedWidth(layout->leftmargin,
529                                                   labelfont);
530                 } else if (layout->labeltype != LABEL_TOP_ENVIRONMENT
531                            && layout->labeltype != LABEL_BIBLIO
532                            && layout->labeltype !=
533                            LABEL_CENTERED_TOP_ENVIRONMENT) {
534                         x += font_metrics::signedWidth(layout->labelindent,
535                                                   labelfont);
536                         x += font_metrics::width(layout->labelsep, labelfont);
537                         x += font_metrics::width(row->par()->getLabelstring(),
538                                             labelfont);
539                 }
540                 break;
541
542         case MARGIN_RIGHT_ADDRESS_BOX:
543         {
544                 // ok, a terrible hack. The left margin depends on the widest
545                 // row in this paragraph. Do not care about footnotes, they
546                 // are *NOT* allowed in the LaTeX realisation of this layout.
547
548                 // find the first row of this paragraph
549                 Row const * tmprow = row;
550                 while (tmprow->previous()
551                        && tmprow->previous()->par() == row->par())
552                         tmprow = tmprow->previous();
553
554                 int minfill = tmprow->fill();
555                 while (tmprow->next() && tmprow->next()->par() == row->par()) {
556                         tmprow = tmprow->next();
557                         if (tmprow->fill() < minfill)
558                                 minfill = tmprow->fill();
559                 }
560
561                 x += font_metrics::signedWidth(layout->leftmargin,
562                         tclass.defaultfont());
563                 x += minfill;
564         }
565         break;
566         }
567
568         if ((workWidth(*bview) > 0) &&
569                 !row->par()->params().leftIndent().zero())
570         {
571                 LyXLength const len = row->par()->params().leftIndent();
572                 int const tw = inset_owner ?
573                         inset_owner->latexTextWidth(bview) : workWidth(*bview);
574                 x += len.inPixels(tw);
575         }
576
577         LyXAlignment align; // wrong type
578
579         if (row->par()->params().align() == LYX_ALIGN_LAYOUT)
580                 align = layout->align;
581         else
582                 align = row->par()->params().align();
583
584         // set the correct parindent
585         if (row->pos() == 0) {
586                 if ((layout->labeltype == LABEL_NO_LABEL
587                      || layout->labeltype == LABEL_TOP_ENVIRONMENT
588                      || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT
589                      || (layout->labeltype == LABEL_STATIC
590                          && layout->latextype == LATEX_ENVIRONMENT
591                          && ! row->par()->isFirstInSequence()))
592                     && align == LYX_ALIGN_BLOCK
593                     && !row->par()->params().noindent()
594                         // in tabulars and ert paragraphs are never indented!
595                         && (!row->par()->inInset() || !row->par()->inInset()->owner() ||
596                                 (row->par()->inInset()->owner()->lyxCode() != Inset::TABULAR_CODE &&
597                                  row->par()->inInset()->owner()->lyxCode() != Inset::ERT_CODE))
598                     && (row->par()->layout() != tclass.defaultLayout() ||
599                         bview->buffer()->params.paragraph_separation ==
600                         BufferParams::PARSEP_INDENT)) {
601                         x += font_metrics::signedWidth(parindent,
602                                                   tclass.defaultfont());
603                 } else if (layout->labeltype == LABEL_BIBLIO) {
604                         // ale970405 Right width for bibitems
605                         x += bibitemMaxWidth(bview, tclass.defaultfont());
606                 }
607         }
608
609         return x;
610 }
611
612
613 int LyXText::rightMargin(Buffer const & buf, Row const & row) const
614 {
615         Inset * ins;
616         if ((row.par()->getChar(row.pos()) == Paragraph::META_INSET) &&
617                 (ins=row.par()->getInset(row.pos())) &&
618                 (ins->needFullRow() || ins->display()))
619                 return PAPER_MARGIN;
620
621         LyXTextClass const & tclass = buf.params.getLyXTextClass();
622         LyXLayout_ptr const & layout = row.par()->layout();
623
624         int x = PAPER_MARGIN
625                 + font_metrics::signedWidth(tclass.rightmargin(),
626                                        tclass.defaultfont());
627
628         // this is the way, LyX handles the LaTeX-Environments.
629         // I have had this idea very late, so it seems to be a
630         // later added hack and this is true
631         if (row.par()->getDepth()) {
632                 // find the next level paragraph
633
634                 Paragraph const * newpar = row.par();
635
636                 do {
637                         newpar = newpar->previous();
638                 } while (newpar
639                          && newpar->getDepth() >= row.par()->getDepth());
640
641                 // make a corresponding row. Needed to call LeftMargin()
642
643                 // check wether it is a sufficent paragraph
644                 if (newpar && newpar->layout()->isEnvironment()) {
645                         Row dummyrow;
646                         dummyrow.par(const_cast<Paragraph *>(newpar));
647                         dummyrow.pos(0);
648                         x = rightMargin(buf, dummyrow);
649                 } else {
650                         // this is no longer an error, because this function
651                         // is used to clear impossible depths after changing
652                         // a layout. Since there is always a redo,
653                         // LeftMargin() is always called
654                         row.par()->params().depth(0);
655                 }
656         }
657
658         //lyxerr << "rightmargin: " << layout->rightmargin << endl;
659         x += font_metrics::signedWidth(layout->rightmargin,
660                                        tclass.defaultfont())
661                 * 4 / (row.par()->getDepth() + 4);
662         return x;
663 }
664
665
666 int LyXText::labelEnd(BufferView & bview, Row const & row) const
667 {
668         if (row.par()->layout()->margintype == MARGIN_MANUAL) {
669                 Row tmprow = row;
670                 tmprow.pos(row.par()->size());
671                 // return the beginning of the body
672                 return leftMargin(&bview, &tmprow);
673         }
674
675         // LabelEnd is only needed if the layout
676         // fills a flushleft label.
677         return 0;
678 }
679
680
681 // get the next breakpoint in a given paragraph
682 pos_type
683 LyXText::nextBreakPoint(BufferView * bview, Row const * row, int width) const
684 {
685         Paragraph * par = row->par();
686
687         if (width < 0)
688                 return par->size();
689
690         pos_type const pos = row->pos();
691
692         // position of the last possible breakpoint
693         // -1 isn't a suitable value, but a flag
694         pos_type last_separator = -1;
695         width -= rightMargin(*bview->buffer(), *row);
696
697         pos_type const body_pos = par->beginningOfBody();
698         LyXLayout_ptr const & layout = par->layout();
699
700         pos_type i = pos;
701
702         if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX) {
703                 // special code for right address boxes, only newlines count
704                 while (i < par->size()) {
705                         if (par->isNewline(i)) {
706                                 last_separator = i;
707                                 i = par->size() - 1; // this means break
708                                 //x = width;
709                         } else if (par->isInset(i) && par->getInset(i)
710                                 && par->getInset(i)->display()) {
711                                 par->getInset(i)->display(false);
712                         }
713                         ++i;
714                 }
715         } else {
716                 // Last position is an invariant
717                 pos_type const last = par->size();
718                 // this is the usual handling
719                 int x = leftMargin(bview, row);
720                 bool doitonetime = true;
721                 while (doitonetime || ((x < width) && (i < last))) {
722                         doitonetime = false;
723                         char const c = par->getChar(i);
724                         Inset * in = 0;
725                         if (c == Paragraph::META_INSET)
726                                 in = par->getInset(i);
727                         if (IsNewlineChar(c)) {
728                                 last_separator = i;
729                                 x = width; // this means break
730                         } else if (in && !in->isChar()) {
731                                 // check wether a Display() inset is
732                                 // valid here. if not, change it to
733                                 // non-display
734                                 if (in->display() &&
735                                     (layout->isCommand() ||
736                                      (layout->labeltype == LABEL_MANUAL
737                                       && i < par->beginningOfBody())))
738                                 {
739                                         // display istn't allowd
740                                         in->display(false);
741                                         x += singleWidth(bview, par, i, c);
742                                 } else if (in->display() || in->needFullRow()) {
743                                         // So break the line here
744                                         if (i == pos) {
745                                                 if (pos < last-1) {
746                                                         last_separator = i;
747                                                         if (par->isLineSeparator(i+1))
748                                                                 ++last_separator;
749                                                 } else
750                                                         last_separator = last; // to avoid extra rows
751                                         } else
752                                                 last_separator = i - 1;
753                                         x = width;  // this means break
754                                 } else {
755                                         x += singleWidth(bview, par, i, c);
756                                         // we have to check this separately as we could have a
757                                         // lineseparator and then the algorithm below would prefer
758                                         // that which IS wrong! We should always break on an inset
759                                         // if it's too long and not on the last separator.
760                                         // Maybe the only exeption is insets used as chars but
761                                         // then we would have to have a special function inside
762                                         // the inset to tell us this. Till then we leave it as
763                                         // it is now. (Jug 20020106)
764                                         if (pos < i && x >= width && last_separator >= 0)
765                                                 last_separator = i - 1;
766                                 }
767                         } else  {
768                                 if (par->isLineSeparator(i))
769                                         last_separator = i;
770                                 x += singleWidth(bview, par, i, c);
771                         }
772                         ++i;
773                         if (i == body_pos) {
774                                 x += font_metrics::width(layout->labelsep,
775                                                     getLabelFont(bview->buffer(), par));
776                                 if (par->isLineSeparator(i - 1))
777                                         x-= singleWidth(bview, par, i - 1);
778                                 int left_margin = labelEnd(*bview, *row);
779                                 if (x < left_margin)
780                                         x = left_margin;
781                         }
782                 }
783                 if ((pos+1 < i) && (last_separator < 0) && (x >= width))
784                         last_separator = i - 2;
785                 else if ((pos < i) && (last_separator < 0) && (x >= width))
786                         last_separator = i - 1;
787                 // end of paragraph is always a suitable separator
788                 else if (i == last && x < width)
789                         last_separator = i;
790         }
791
792         // well, if last_separator is still 0, the line isn't breakable.
793         // don't care and cut simply at the end
794         if (last_separator < 0) {
795                 last_separator = i;
796         }
797
798         // manual labels cannot be broken in LaTeX, do not care
799         if (body_pos && last_separator < body_pos)
800                 last_separator = body_pos - 1;
801
802         return last_separator;
803 }
804
805
806 // returns the minimum space a row needs on the screen in pixel
807 int LyXText::fill(BufferView & bview, Row & row, int paper_width) const
808 {
809         if (paper_width < 0)
810                 return 0;
811
812         int w;
813         // get the pure distance
814         pos_type const last = row.lastPrintablePos();
815
816         // special handling of the right address boxes
817         if (row.par()->layout()->margintype == MARGIN_RIGHT_ADDRESS_BOX) {
818                 int const tmpfill = row.fill();
819                 row.fill(0); // the minfill in MarginLeft()
820                 w = leftMargin(&bview, &row);
821                 row.fill(tmpfill);
822         } else
823                 w = leftMargin(&bview, &row);
824
825         Paragraph * par = row.par();
826         LyXLayout_ptr const & layout = par->layout();
827
828         pos_type const body_pos = par->beginningOfBody();
829         pos_type i = row.pos();
830
831         while (i <= last) {
832                 if (body_pos > 0 && i == body_pos) {
833                         w += font_metrics::width(layout->labelsep, getLabelFont(bview.buffer(), par));
834                         if (par->isLineSeparator(i - 1))
835                                 w -= singleWidth(&bview, par, i - 1);
836                         int left_margin = labelEnd(bview, row);
837                         if (w < left_margin)
838                                 w = left_margin;
839                 }
840                 w += singleWidth(&bview, par, i);
841                 ++i;
842         }
843         if (body_pos > 0 && body_pos > last) {
844                 w += font_metrics::width(layout->labelsep, getLabelFont(bview.buffer(), par));
845                 if (last >= 0 && par->isLineSeparator(last))
846                         w -= singleWidth(&bview, par, last);
847                 int const left_margin = labelEnd(bview, row);
848                 if (w < left_margin)
849                         w = left_margin;
850         }
851
852         int const fill = paper_width - w - rightMargin(*bview.buffer(), row);
853         return fill;
854 }
855
856
857 // returns the minimum space a manual label needs on the screen in pixel
858 int LyXText::labelFill(BufferView & bview, Row const & row) const
859 {
860         pos_type last = row.par()->beginningOfBody();
861
862         lyx::Assert(last > 0);
863
864         // -1 because a label ends either with a space that is in the label,
865         // or with the beginning of a footnote that is outside the label.
866         --last;
867
868         // a separator at this end does not count
869         if (row.par()->isLineSeparator(last))
870                 --last;
871
872         int w = 0;
873         pos_type i = row.pos();
874         while (i <= last) {
875                 w += singleWidth(&bview, row.par(), i);
876                 ++i;
877         }
878
879         int fill = 0;
880         string const & labwidstr = row.par()->params().labelWidthString();
881         if (!labwidstr.empty()) {
882                 LyXFont const labfont = getLabelFont(bview.buffer(), row.par());
883                 int const labwidth = font_metrics::width(labwidstr, labfont);
884                 fill = max(labwidth - w, 0);
885         }
886
887         return fill;
888 }
889
890
891 LColor::color LyXText::backgroundColor() const
892 {
893         if (inset_owner)
894                 return inset_owner->backgroundColor();
895         else
896                 return LColor::background;
897 }
898
899 void LyXText::setHeightOfRow(BufferView * bview, Row * row) const
900 {
901         // get the maximum ascent and the maximum descent
902         int asc = 0;
903         int desc = 0;
904         float layoutasc = 0;
905         float layoutdesc = 0;
906         float tmptop = 0;
907         LyXFont tmpfont;
908         Inset * tmpinset = 0;
909
910         // ok , let us initialize the maxasc and maxdesc value.
911         // This depends in LaTeX of the font of the last character
912         // in the paragraph. The hack below is necessary because
913         // of the possibility of open footnotes
914
915         // Correction: only the fontsize count. The other properties
916         //  are taken from the layoutfont. Nicer on the screen :)
917         Paragraph * par = row->par();
918         Paragraph * firstpar = row->par();
919
920         LyXLayout_ptr const & layout = firstpar->layout();
921
922         // as max get the first character of this row then it can increase but not
923         // decrease the height. Just some point to start with so we don't have to
924         // do the assignment below too often.
925         LyXFont font = getFont(bview->buffer(), par, row->pos());
926         LyXFont::FONT_SIZE const tmpsize = font.size();
927         font = getLayoutFont(bview->buffer(), par);
928         LyXFont::FONT_SIZE const size = font.size();
929         font.setSize(tmpsize);
930
931         LyXFont labelfont = getLabelFont(bview->buffer(), par);
932
933         float spacing_val = 1.0;
934         if (!row->par()->params().spacing().isDefault()) {
935                 spacing_val = row->par()->params().spacing().getValue();
936         } else {
937                 spacing_val = bview->buffer()->params.spacing.getValue();
938         }
939         //lyxerr << "spacing_val = " << spacing_val << endl;
940
941         int maxasc = int(font_metrics::maxAscent(font) *
942                          layout->spacing.getValue() *
943                          spacing_val);
944         int maxdesc = int(font_metrics::maxDescent(font) *
945                           layout->spacing.getValue() *
946                           spacing_val);
947
948         pos_type const pos_end = row->lastPos();
949         int labeladdon = 0;
950         int maxwidth = 0;
951
952         // Check if any insets are larger
953         for (pos_type pos = row->pos(); pos <= pos_end; ++pos) {
954                 if (row->par()->isInset(pos)) {
955                         tmpfont = getFont(bview->buffer(), row->par(), pos);
956                         tmpinset = row->par()->getInset(pos);
957                         if (tmpinset) {
958 #if 1 // this is needed for deep update on initialitation
959                                 tmpinset->update(bview, tmpfont);
960 #endif
961                                 asc = tmpinset->ascent(bview, tmpfont);
962                                 desc = tmpinset->descent(bview, tmpfont);
963                                 maxwidth += tmpinset->width(bview, tmpfont);
964                                 maxasc = max(maxasc, asc);
965                                 maxdesc = max(maxdesc, desc);
966                         }
967                 } else {
968                         maxwidth += singleWidth(bview, row->par(), pos);
969                 }
970         }
971
972         // Check if any custom fonts are larger (Asger)
973         // This is not completely correct, but we can live with the small,
974         // cosmetic error for now.
975         LyXFont::FONT_SIZE maxsize =
976                 row->par()->highestFontInRange(row->pos(), pos_end, size);
977         if (maxsize > font.size()) {
978                 font.setSize(maxsize);
979
980                 asc = font_metrics::maxAscent(font);
981                 desc = font_metrics::maxDescent(font);
982                 if (asc > maxasc)
983                         maxasc = asc;
984                 if (desc > maxdesc)
985                         maxdesc = desc;
986         }
987
988         // This is nicer with box insets:
989         ++maxasc;
990         ++maxdesc;
991
992         row->ascent_of_text(maxasc);
993
994         // is it a top line?
995         if (!row->pos() && (row->par() == firstpar)) {
996
997                 // some parksips VERY EASY IMPLEMENTATION
998                 if (bview->buffer()->params.paragraph_separation ==
999                         BufferParams::PARSEP_SKIP)
1000                 {
1001                         if (layout->isParagraph()
1002                                 && firstpar->getDepth() == 0
1003                                 && firstpar->previous())
1004                         {
1005                                 maxasc += bview->buffer()->params.getDefSkip().inPixels(*bview);
1006                         } else if (firstpar->previous() &&
1007                                    firstpar->previous()->layout()->isParagraph() &&
1008                                    firstpar->previous()->getDepth() == 0)
1009                         {
1010                                 // is it right to use defskip here too? (AS)
1011                                 maxasc += bview->buffer()->params.getDefSkip().inPixels(*bview);
1012                         }
1013                 }
1014
1015                 // the top margin
1016                 if (!row->par()->previous() && isTopLevel())
1017                         maxasc += PAPER_MARGIN;
1018
1019                 // add the vertical spaces, that the user added
1020                 maxasc += getLengthMarkerHeight(*bview, firstpar->params().spaceTop());
1021
1022                 // do not forget the DTP-lines!
1023                 // there height depends on the font of the nearest character
1024                 if (firstpar->params().lineTop())
1025
1026                         maxasc += 2 * font_metrics::ascent('x', getFont(bview->buffer(),
1027                                         firstpar, 0));
1028                 // and now the pagebreaks
1029                 if (firstpar->params().pagebreakTop())
1030                         maxasc += 3 * defaultRowHeight();
1031
1032                 // This is special code for the chapter, since the label of this
1033                 // layout is printed in an extra row
1034                 if (layout->labeltype == LABEL_COUNTER_CHAPTER
1035                         && bview->buffer()->params.secnumdepth >= 0)
1036                 {
1037                         float spacing_val = 1.0;
1038                         if (!row->par()->params().spacing().isDefault()) {
1039                                 spacing_val = row->par()->params().spacing().getValue();
1040                         } else {
1041                                 spacing_val = bview->buffer()->params.spacing.getValue();
1042                         }
1043
1044                         labeladdon = int(font_metrics::maxDescent(labelfont) *
1045                                          layout->spacing.getValue() *
1046                                          spacing_val)
1047                                 + int(font_metrics::maxAscent(labelfont) *
1048                                       layout->spacing.getValue() *
1049                                       spacing_val);
1050                 }
1051
1052                 // special code for the top label
1053                 if ((layout->labeltype == LABEL_TOP_ENVIRONMENT
1054                      || layout->labeltype == LABEL_BIBLIO
1055                      || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
1056                     && row->par()->isFirstInSequence()
1057                     && !row->par()->getLabelstring().empty())
1058                 {
1059                         float spacing_val = 1.0;
1060                         if (!row->par()->params().spacing().isDefault()) {
1061                                 spacing_val = row->par()->params().spacing().getValue();
1062                         } else {
1063                                 spacing_val = bview->buffer()->params.spacing.getValue();
1064                         }
1065
1066                         labeladdon = int(
1067                                 (font_metrics::maxAscent(labelfont) *
1068                                  layout->spacing.getValue() *
1069                                  spacing_val)
1070                                 +(font_metrics::maxDescent(labelfont) *
1071                                   layout->spacing.getValue() *
1072                                   spacing_val)
1073                                 + layout->topsep * defaultRowHeight()
1074                                 + layout->labelbottomsep * defaultRowHeight());
1075                 }
1076
1077                 // and now the layout spaces, for example before and after a section,
1078                 // or between the items of a itemize or enumerate environment
1079
1080                 if (!firstpar->params().pagebreakTop()) {
1081                         Paragraph * prev = row->par()->previous();
1082                         if (prev)
1083                                 prev = row->par()->depthHook(row->par()->getDepth());
1084                         if (prev && prev->layout() == firstpar->layout() &&
1085                                 prev->getDepth() == firstpar->getDepth() &&
1086                                 prev->getLabelWidthString() == firstpar->getLabelWidthString())
1087                         {
1088                                 layoutasc = (layout->itemsep * defaultRowHeight());
1089                         } else if (row->previous()) {
1090                                 tmptop = layout->topsep;
1091
1092                                 if (row->previous()->par()->getDepth() >= row->par()->getDepth())
1093                                         tmptop -= row->previous()->par()->layout()->bottomsep;
1094
1095                                 if (tmptop > 0)
1096                                         layoutasc = (tmptop * defaultRowHeight());
1097                         } else if (row->par()->params().lineTop()) {
1098                                 tmptop = layout->topsep;
1099
1100                                 if (tmptop > 0)
1101                                         layoutasc = (tmptop * defaultRowHeight());
1102                         }
1103
1104                         prev = row->par()->outerHook();
1105                         if (prev)  {
1106                                 maxasc += int(prev->layout()->parsep * defaultRowHeight());
1107                         } else {
1108                                 if (firstpar->previous() &&
1109                                         firstpar->previous()->getDepth() == 0 &&
1110                                         firstpar->previous()->layout() !=
1111                                         firstpar->layout())
1112                                 {
1113                                         // avoid parsep
1114                                 } else if (firstpar->previous()) {
1115                                         maxasc += int(layout->parsep * defaultRowHeight());
1116                                 }
1117                         }
1118                 }
1119         }
1120
1121         // is it a bottom line?
1122         if (row->par() == par
1123                 && (!row->next() || row->next()->par() != row->par())) {
1124                 // the bottom margin
1125                 if (!par->next() && isTopLevel())
1126                         maxdesc += PAPER_MARGIN;
1127
1128                 // add the vertical spaces, that the user added
1129                 maxdesc += getLengthMarkerHeight(*bview, firstpar->params().spaceBottom());
1130
1131                 // do not forget the DTP-lines!
1132                 // there height depends on the font of the nearest character
1133                 if (firstpar->params().lineBottom())
1134                         maxdesc += 2 * font_metrics::ascent('x',
1135                                                        getFont(bview->buffer(),
1136                                                                par,
1137                                                                max(pos_type(0), par->size() - 1)));
1138
1139                 // and now the pagebreaks
1140                 if (firstpar->params().pagebreakBottom())
1141                         maxdesc += 3 * defaultRowHeight();
1142
1143                 // and now the layout spaces, for example before and after
1144                 // a section, or between the items of a itemize or enumerate
1145                 // environment
1146                 if (!firstpar->params().pagebreakBottom()
1147                     && row->par()->next()) {
1148                         Paragraph * nextpar = row->par()->next();
1149                         Paragraph * comparepar = row->par();
1150                         float usual = 0;
1151                         float unusual = 0;
1152
1153                         if (comparepar->getDepth() > nextpar->getDepth()) {
1154                                 usual = (comparepar->layout()->bottomsep * defaultRowHeight());
1155                                 comparepar = comparepar->depthHook(nextpar->getDepth());
1156                                 if (comparepar->layout()!= nextpar->layout()
1157                                         || nextpar->getLabelWidthString() !=
1158                                         comparepar->getLabelWidthString())
1159                                 {
1160                                         unusual = (comparepar->layout()->bottomsep * defaultRowHeight());
1161                                 }
1162                                 if (unusual > usual)
1163                                         layoutdesc = unusual;
1164                                 else
1165                                         layoutdesc = usual;
1166                         } else if (comparepar->getDepth() ==  nextpar->getDepth()) {
1167
1168                                 if (comparepar->layout() != nextpar->layout()
1169                                         || nextpar->getLabelWidthString() !=
1170                                         comparepar->getLabelWidthString())
1171                                         layoutdesc = int(comparepar->layout()->bottomsep * defaultRowHeight());
1172                         }
1173                 }
1174         }
1175
1176         // incalculate the layout spaces
1177         maxasc += int(layoutasc * 2 / (2 + firstpar->getDepth()));
1178         maxdesc += int(layoutdesc * 2 / (2 + firstpar->getDepth()));
1179
1180         // calculate the new height of the text
1181         height -= row->height();
1182
1183         row->height(maxasc + maxdesc + labeladdon);
1184         row->baseline(maxasc + labeladdon);
1185
1186         height += row->height();
1187
1188         row->top_of_text(row->baseline() - font_metrics::maxAscent(font));
1189
1190         float x = 0;
1191         if (layout->margintype != MARGIN_RIGHT_ADDRESS_BOX) {
1192                 float dummy;
1193                 // this IS needed
1194                 row->width(maxwidth);
1195                 prepareToPrint(bview, row, x, dummy, dummy, dummy, false);
1196         }
1197         row->width(int(maxwidth + x));
1198         if (inset_owner) {
1199                 Row * r = firstrow;
1200                 width = max(0, workWidth(*bview));
1201                 while (r) {
1202                         if (r->width() > width)
1203                                 width = r->width();
1204                         r = r->next();
1205                 }
1206         }
1207 }
1208
1209
1210 // Appends the implicit specified paragraph behind the specified row,
1211 // start at the implicit given position
1212 void LyXText::appendParagraph(BufferView * bview, Row * row) const
1213 {
1214         bool not_ready = true;
1215
1216         // The last character position of a paragraph is an invariant so we can
1217         // safely get it here. (Asger)
1218         pos_type const lastposition = row->par()->size();
1219         do {
1220                 // Get the next breakpoint
1221                 pos_type z = nextBreakPoint(bview, row, workWidth(*bview));
1222
1223                 Row * tmprow = row;
1224
1225                 // Insert the new row
1226                 if (z < lastposition) {
1227                         ++z;
1228                         insertRow(row, row->par(), z);
1229                         row = row->next();
1230
1231                         row->height(0);
1232                 } else
1233                         not_ready = false;
1234
1235                 // Set the dimensions of the row
1236                 // fixed fill setting now by calling inset->update() in
1237                 // SingleWidth when needed!
1238                 tmprow->fill(fill(*bview, *tmprow, workWidth(*bview)));
1239                 setHeightOfRow(bview, tmprow);
1240
1241         } while (not_ready);
1242 }
1243
1244
1245 // Do we even need this at all ? Code that uses  RowPainter *already*
1246 // sets need_break_row when it sees a CHANGED_IN_DRAW, though not
1247 // quite like this
1248 void LyXText::markChangeInDraw(BufferView * bv, Row * row, Row * prev)
1249 {
1250         if (prev && prev->par() == row->par()) {
1251                 breakAgainOneRow(bv, prev);
1252                 if (prev->next() != row) {
1253                         // breakAgainOneRow() has removed row_
1254                         need_break_row = prev;
1255                 } else {
1256                         need_break_row = row;
1257                 }
1258         } else if (!prev) {
1259                 need_break_row = firstrow;
1260         } else {
1261                 need_break_row = prev->next();
1262         }
1263         setCursor(bv, cursor.par(), cursor.pos());
1264         /* FIXME */
1265 }
1266
1267
1268 void LyXText::breakAgain(BufferView * bview, Row * row) const
1269 {
1270         bool not_ready = true;
1271
1272         do  {
1273                 // get the next breakpoint
1274                 pos_type z = nextBreakPoint(bview, row, workWidth(*bview));
1275                 Row * tmprow = row;
1276
1277                 if (z < row->par()->size()) {
1278                         if (!row->next() || (row->next() && row->next()->par() != row->par())) {
1279                                 // insert a new row
1280                                 ++z;
1281                                 insertRow(row, row->par(), z);
1282                                 row = row->next();
1283                                 row->height(0);
1284                         } else  {
1285                                 row = row->next();
1286                                 ++z;
1287                                 if (row->pos() == z)
1288                                         not_ready = false;     // the rest will not change
1289                                 else {
1290                                         row->pos(z);
1291                                 }
1292                         }
1293                 } else {
1294                         // if there are some rows too much, delete them
1295                         // only if you broke the whole paragraph!
1296                         Row * tmprow2 = row;
1297                         while (tmprow2->next() && tmprow2->next()->par() == row->par()) {
1298                                 tmprow2 = tmprow2->next();
1299                         }
1300                         while (tmprow2 != row) {
1301                                 tmprow2 = tmprow2->previous();
1302                                 removeRow(tmprow2->next());
1303                         }
1304                         not_ready = false;
1305                 }
1306
1307                 // set the dimensions of the row
1308                 tmprow->fill(fill(*bview, *tmprow, workWidth(*bview)));
1309                 setHeightOfRow(bview, tmprow);
1310         } while (not_ready);
1311 }
1312
1313
1314 // this is just a little changed version of break again
1315 void LyXText::breakAgainOneRow(BufferView * bview, Row * row)
1316 {
1317         // get the next breakpoint
1318         pos_type z = nextBreakPoint(bview, row, workWidth(*bview));
1319         Row * tmprow = row;
1320
1321         if (z < row->par()->size()) {
1322                 if (!row->next()
1323                     || (row->next() && row->next()->par() != row->par())) {
1324                         // insert a new row
1325                         ++z;
1326                         insertRow(row, row->par(), z);
1327                         row = row->next();
1328                         row->height(0);
1329                 } else  {
1330                         row = row->next();
1331                         ++z;
1332                         if (row->pos() != z)
1333                                 row->pos(z);
1334                 }
1335         } else {
1336                 // if there are some rows too much, delete them
1337                 // only if you broke the whole paragraph!
1338                 Row * tmprow2 = row;
1339                 while (tmprow2->next()
1340                        && tmprow2->next()->par() == row->par()) {
1341                         tmprow2 = tmprow2->next();
1342                 }
1343                 while (tmprow2 != row) {
1344                         tmprow2 = tmprow2->previous();
1345                         removeRow(tmprow2->next());
1346                 }
1347         }
1348
1349         // set the dimensions of the row
1350         tmprow->fill(fill(*bview, *tmprow, workWidth(*bview)));
1351         setHeightOfRow(bview, tmprow);
1352 }
1353
1354
1355 void LyXText::breakParagraph(BufferView * bview,
1356                              ParagraphList & paragraphs, char keep_layout)
1357 {
1358         // allow only if at start or end, or all previous is new text
1359         if (cursor.pos() && cursor.pos() != cursor.par()->size()
1360                 && cursor.par()->isChangeEdited(0, cursor.pos()))
1361                 return;
1362
1363         LyXTextClass const & tclass =
1364                 bview->buffer()->params.getLyXTextClass();
1365         LyXLayout_ptr const & layout = cursor.par()->layout();
1366
1367         // this is only allowed, if the current paragraph is not empty or caption
1368         // and if it has not the keepempty flag aktive
1369         if (cursor.par()->empty()
1370            && layout->labeltype != LABEL_SENSITIVE
1371            && !layout->keepempty)
1372                 return;
1373
1374         setUndo(bview, Undo::FINISH, cursor.par(), cursor.par()->next());
1375
1376         // Always break behind a space
1377         //
1378         // It is better to erase the space (Dekel)
1379         if (cursor.pos() < cursor.par()->size()
1380              && cursor.par()->isLineSeparator(cursor.pos()))
1381            cursor.par()->erase(cursor.pos());
1382         // cursor.pos(cursor.pos() + 1);
1383
1384         // break the paragraph
1385         if (keep_layout)
1386                 keep_layout = 2;
1387         else
1388                 keep_layout = layout->isEnvironment();
1389
1390         // we need to set this before we insert the paragraph. IMO the
1391         // breakParagraph call should return a bool if it inserts the
1392         // paragraph before or behind and we should react on that one
1393         // but we can fix this in 1.3.0 (Jug 20020509)
1394         bool const isempty = (layout->keepempty && cursor.par()->empty());
1395         ::breakParagraph(bview->buffer()->params, paragraphs, cursor.par(), cursor.pos(),
1396                        keep_layout);
1397
1398         // well this is the caption hack since one caption is really enough
1399         if (layout->labeltype == LABEL_SENSITIVE) {
1400                 if (!cursor.pos())
1401                         // set to standard-layout
1402                         cursor.par()->applyLayout(tclass.defaultLayout());
1403                 else
1404                         // set to standard-layout
1405                         cursor.par()->next()->applyLayout(tclass.defaultLayout());
1406         }
1407
1408         // if the cursor is at the beginning of a row without prior newline,
1409         // move one row up!
1410         // This touches only the screen-update. Otherwise we would may have
1411         // an empty row on the screen
1412         if (cursor.pos() && !cursor.row()->par()->isNewline(cursor.row()->pos() - 1)
1413                          && cursor.row()->pos() == cursor.pos())
1414         {
1415                 cursorLeft(bview);
1416         }
1417
1418         status(bview, LyXText::NEED_MORE_REFRESH);
1419         refresh_row = cursor.row();
1420         refresh_y = cursor.y() - cursor.row()->baseline();
1421
1422         // Do not forget the special right address boxes
1423         if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX) {
1424                 while (refresh_row->previous() &&
1425                        refresh_row->previous()->par() == refresh_row->par())
1426                 {
1427                         refresh_row = refresh_row->previous();
1428                         refresh_y -= refresh_row->height();
1429                 }
1430         }
1431         removeParagraph(cursor.row());
1432
1433         // set the dimensions of the cursor row
1434         cursor.row()->fill(fill(*bview, *cursor.row(), workWidth(*bview)));
1435
1436         setHeightOfRow(bview, cursor.row());
1437
1438 #warning Trouble Point! (Lgb)
1439         // When ::breakParagraph is called from within an inset we must
1440         // ensure that the correct ParagraphList is used. Today that is not
1441         // the case and the Buffer::paragraphs is used. Not good. (Lgb)
1442         while (!cursor.par()->next()->empty()
1443           && cursor.par()->next()->isNewline(0))
1444            cursor.par()->next()->erase(0);
1445
1446         insertParagraph(bview, cursor.par()->next(), cursor.row());
1447
1448         updateCounters(bview);
1449
1450         // This check is necessary. Otherwise the new empty paragraph will
1451         // be deleted automatically. And it is more friendly for the user!
1452         if (cursor.pos() || isempty)
1453                 setCursor(bview, cursor.par()->next(), 0);
1454         else
1455                 setCursor(bview, cursor.par(), 0);
1456
1457         if (cursor.row()->next())
1458                 breakAgain(bview, cursor.row()->next());
1459
1460         need_break_row = 0;
1461 }
1462
1463
1464 // Just a macro to make some thing easier.
1465 void LyXText::redoParagraph(BufferView * bview) const
1466 {
1467         clearSelection();
1468         redoParagraphs(bview, cursor, cursor.par()->next());
1469         setCursorIntern(bview, cursor.par(), cursor.pos());
1470 }
1471
1472
1473 // insert a character, moves all the following breaks in the
1474 // same Paragraph one to the right and make a rebreak
1475 void LyXText::insertChar(BufferView * bview, char c)
1476 {
1477         setUndo(bview, Undo::INSERT, cursor.par(), cursor.par()->next());
1478
1479         // When the free-spacing option is set for the current layout,
1480         // disable the double-space checking
1481
1482         bool const freeSpacing = cursor.row()->par()->layout()->free_spacing ||
1483                 cursor.row()->par()->isFreeSpacing();
1484
1485         if (lyxrc.auto_number) {
1486                 static string const number_operators = "+-/*";
1487                 static string const number_unary_operators = "+-";
1488                 static string const number_seperators = ".,:";
1489
1490                 if (current_font.number() == LyXFont::ON) {
1491                         if (!IsDigit(c) && !contains(number_operators, c) &&
1492                             !(contains(number_seperators, c) &&
1493                               cursor.pos() >= 1 &&
1494                               cursor.pos() < cursor.par()->size() &&
1495                               getFont(bview->buffer(),
1496                                       cursor.par(),
1497                                       cursor.pos()).number() == LyXFont::ON &&
1498                               getFont(bview->buffer(),
1499                                       cursor.par(),
1500                                       cursor.pos() - 1).number() == LyXFont::ON)
1501                            )
1502                                 number(bview); // Set current_font.number to OFF
1503                 } else if (IsDigit(c) &&
1504                            real_current_font.isVisibleRightToLeft()) {
1505                         number(bview); // Set current_font.number to ON
1506
1507                         if (cursor.pos() > 0) {
1508                                 char const c = cursor.par()->getChar(cursor.pos() - 1);
1509                                 if (contains(number_unary_operators, c) &&
1510                                     (cursor.pos() == 1 ||
1511                                      cursor.par()->isSeparator(cursor.pos() - 2) ||
1512                                      cursor.par()->isNewline(cursor.pos() - 2))
1513                                   ) {
1514                                         setCharFont(bview->buffer(),
1515                                                     cursor.par(),
1516                                                     cursor.pos() - 1,
1517                                                     current_font);
1518                                 } else if (contains(number_seperators, c) &&
1519                                            cursor.pos() >= 2 &&
1520                                            getFont(bview->buffer(),
1521                                                    cursor.par(),
1522                                                    cursor.pos() - 2).number() == LyXFont::ON) {
1523                                         setCharFont(bview->buffer(),
1524                                                     cursor.par(),
1525                                                     cursor.pos() - 1,
1526                                                     current_font);
1527                                 }
1528                         }
1529                 }
1530         }
1531
1532
1533         // First check, if there will be two blanks together or a blank at
1534         // the beginning of a paragraph.
1535         // I decided to handle blanks like normal characters, the main
1536         // difference are the special checks when calculating the row.fill
1537         // (blank does not count at the end of a row) and the check here
1538
1539         // The bug is triggered when we type in a description environment:
1540         // The current_font is not changed when we go from label to main text
1541         // and it should (along with realtmpfont) when we type the space.
1542         // CHECK There is a bug here! (Asger)
1543
1544         LyXFont realtmpfont = real_current_font;
1545         LyXFont rawtmpfont = current_font;
1546         // store the current font.  This is because of the use of cursor
1547         // movements. The moving cursor would refresh the current font
1548
1549         // Get the font that is used to calculate the baselineskip
1550         pos_type const lastpos = cursor.par()->size();
1551         LyXFont rawparfont =
1552                 cursor.par()->getFontSettings(bview->buffer()->params,
1553                                               lastpos - 1);
1554
1555         bool jumped_over_space = false;
1556
1557         if (!freeSpacing && IsLineSeparatorChar(c)) {
1558                 if ((cursor.pos() > 0
1559                      && cursor.par()->isLineSeparator(cursor.pos() - 1))
1560                     || (cursor.pos() > 0
1561                         && cursor.par()->isNewline(cursor.pos() - 1))
1562                     || (cursor.pos() == 0)) {
1563                         static bool sent_space_message = false;
1564                         if (!sent_space_message) {
1565                                 if (cursor.pos() == 0)
1566                                         bview->owner()->message(_("You cannot insert a space at the beginning of a paragraph. Please read the Tutorial."));
1567                                 else
1568                                         bview->owner()->message(_("You cannot type two spaces this way. Please read the Tutorial."));
1569                                 sent_space_message = true;
1570                         }
1571                         charInserted();
1572                         return;
1573                 }
1574         } else if (IsNewlineChar(c)) {
1575                 if (cursor.pos() <= cursor.par()->beginningOfBody()) {
1576                         charInserted();
1577                         return;
1578                 }
1579                 // No newline at first position of a paragraph or behind labels.
1580                 // TeX does not allow that
1581
1582                 if (cursor.pos() < cursor.par()->size() &&
1583                     cursor.par()->isLineSeparator(cursor.pos()))
1584                         // newline always after a blank!
1585                         cursorRight(bview);
1586                 cursor.row()->fill(-1);        // to force a new break
1587         }
1588
1589         // the display inset stuff
1590         if (cursor.row()->par()->isInset(cursor.row()->pos())) {
1591                 Inset * inset = cursor.row()->par()->getInset(cursor.row()->pos());
1592                 if (inset && (inset->display() || inset->needFullRow())) {
1593                         // force a new break
1594                         cursor.row()->fill(-1); // to force a new break
1595                 }
1596         }
1597
1598         // get the cursor row fist
1599         Row * row = cursor.row();
1600         int y = cursor.y() - row->baseline();
1601         if (c != Paragraph::META_INSET) {
1602                 // Here case LyXText::InsertInset  already insertet the character
1603                 cursor.par()->insertChar(cursor.pos(), c);
1604         }
1605         setCharFont(bview->buffer(), cursor.par(), cursor.pos(), rawtmpfont);
1606
1607         if (!jumped_over_space) {
1608                 // refresh the positions
1609                 Row * tmprow = row;
1610                 while (tmprow->next() && tmprow->next()->par() == row->par()) {
1611                         tmprow = tmprow->next();
1612                         tmprow->pos(tmprow->pos() + 1);
1613                 }
1614         }
1615
1616         // Is there a break one row above
1617         if (row->previous() && row->previous()->par() == row->par()
1618             && (cursor.par()->isLineSeparator(cursor.pos())
1619                 || cursor.par()->isNewline(cursor.pos())
1620                 || ((cursor.pos() < cursor.par()->size()) &&
1621                     cursor.par()->isInset(cursor.pos()+1))
1622                 || cursor.row()->fill() == -1))
1623         {
1624                 pos_type z = nextBreakPoint(bview,
1625                                                            row->previous(),
1626                                                            workWidth(*bview));
1627                 if (z >= row->pos()) {
1628                         row->pos(z + 1);
1629
1630                         // set the dimensions of the row above
1631                         row->previous()->fill(fill(*bview,
1632                                                    *row->previous(),
1633                                                    workWidth(*bview)));
1634
1635                         setHeightOfRow(bview, row->previous());
1636
1637                         y -= row->previous()->height();
1638                         refresh_y = y;
1639                         refresh_row = row->previous();
1640                         status(bview, LyXText::NEED_MORE_REFRESH);
1641
1642                         breakAgainOneRow(bview, row);
1643
1644                         current_font = rawtmpfont;
1645                         real_current_font = realtmpfont;
1646                         setCursor(bview, cursor.par(), cursor.pos() + 1,
1647                                   false, cursor.boundary());
1648                         // cursor MUST be in row now.
1649
1650                         if (row->next() && row->next()->par() == row->par())
1651                                 need_break_row = row->next();
1652                         else
1653                                 need_break_row = 0;
1654
1655                         // check, wether the last characters font has changed.
1656                         if (cursor.pos() && cursor.pos() == cursor.par()->size()
1657                             && rawparfont != rawtmpfont)
1658                                 redoHeightOfParagraph(bview, cursor);
1659
1660                         charInserted();
1661                         return;
1662                 }
1663         }
1664
1665         // recalculate the fill of the row
1666         if (row->fill() >= 0) {
1667                 // needed because a newline will set fill to -1. Otherwise
1668                 // we would not get a rebreak!
1669                 row->fill(fill(*bview, *row, workWidth(*bview)));
1670         }
1671
1672         if (c == Paragraph::META_INSET || row->fill() < 0) {
1673                 refresh_y = y;
1674                 refresh_row = row;
1675                 status(bview, LyXText::NEED_MORE_REFRESH);
1676                 breakAgainOneRow(bview, row);
1677                 // will the cursor be in another row now?
1678                 if (row->lastPos() <= cursor.pos() + 1 && row->next()) {
1679                         if (row->next() && row->next()->par() == row->par())
1680                                 // this should always be true
1681                                 row = row->next();
1682                         breakAgainOneRow(bview, row);
1683                 }
1684                 current_font = rawtmpfont;
1685                 real_current_font = realtmpfont;
1686
1687                 setCursor(bview, cursor.par(), cursor.pos() + 1, false,
1688                           cursor.boundary());
1689                 if (isBoundary(bview->buffer(), cursor.par(), cursor.pos())
1690                     != cursor.boundary())
1691                         setCursor(bview, cursor.par(), cursor.pos(), false,
1692                           !cursor.boundary());
1693                 if (row->next() && row->next()->par() == row->par())
1694                         need_break_row = row->next();
1695                 else
1696                         need_break_row = 0;
1697         } else {
1698                 refresh_y = y;
1699                 refresh_row = row;
1700
1701                 int const tmpheight = row->height();
1702                 setHeightOfRow(bview, row);
1703                 if (tmpheight == row->height())
1704                         status(bview, LyXText::NEED_VERY_LITTLE_REFRESH);
1705                 else
1706                         status(bview, LyXText::NEED_MORE_REFRESH);
1707
1708                 current_font = rawtmpfont;
1709                 real_current_font = realtmpfont;
1710                 setCursor(bview, cursor.par(), cursor.pos() + 1, false,
1711                           cursor.boundary());
1712         }
1713
1714         // check, wether the last characters font has changed.
1715         if (cursor.pos() && cursor.pos() == cursor.par()->size()
1716             && rawparfont != rawtmpfont) {
1717                 redoHeightOfParagraph(bview, cursor);
1718         } else {
1719                 // now the special right address boxes
1720                 if (cursor.par()->layout()->margintype
1721                     == MARGIN_RIGHT_ADDRESS_BOX) {
1722                         redoDrawingOfParagraph(bview, cursor);
1723                 }
1724         }
1725
1726         charInserted();
1727 }
1728
1729
1730 void LyXText::charInserted()
1731 {
1732         // Here we could call FinishUndo for every 20 characters inserted.
1733         // This is from my experience how emacs does it.
1734         static unsigned int counter;
1735         if (counter < 20) {
1736                 ++counter;
1737         } else {
1738                 finishUndo();
1739                 counter = 0;
1740         }
1741 }
1742
1743
1744 void LyXText::prepareToPrint(BufferView * bview,
1745                              Row * row, float & x,
1746                              float & fill_separator,
1747                              float & fill_hfill,
1748                              float & fill_label_hfill,
1749                              bool bidi) const
1750 {
1751         float nlh;
1752         float ns;
1753
1754         float w = row->fill();
1755         fill_hfill = 0;
1756         fill_label_hfill = 0;
1757         fill_separator = 0;
1758         fill_label_hfill = 0;
1759
1760         bool const is_rtl =
1761                 row->par()->isRightToLeftPar(bview->buffer()->params);
1762         if (is_rtl) {
1763                 x = (workWidth(*bview) > 0)
1764                         ? rightMargin(*bview->buffer(), *row) : 0;
1765         } else
1766                 x = (workWidth(*bview) > 0)
1767                         ? leftMargin(bview, row) : 0;
1768
1769         // is there a manual margin with a manual label
1770         LyXLayout_ptr const & layout = row->par()->layout();
1771
1772         if (layout->margintype == MARGIN_MANUAL
1773             && layout->labeltype == LABEL_MANUAL) {
1774                 /// We might have real hfills in the label part
1775                 nlh = row->numberOfLabelHfills();
1776
1777                 // A manual label par (e.g. List) has an auto-hfill
1778                 // between the label text and the body of the
1779                 // paragraph too.
1780                 // But we don't want to do this auto hfill if the par
1781                 // is empty.
1782                 if (!row->par()->empty())
1783                         ++nlh;
1784                         
1785                 if (nlh && !row->par()->getLabelWidthString().empty()) {
1786                         fill_label_hfill = labelFill(*bview, *row) / nlh;
1787                 }
1788         }
1789
1790         // are there any hfills in the row?
1791         float const nh = row->numberOfHfills();
1792
1793         if (nh) {
1794                 if (w > 0)
1795                         fill_hfill = w / nh;
1796         // we don't have to look at the alignment if it is ALIGN_LEFT and
1797         // if the row is already larger then the permitted width as then
1798         // we force the LEFT_ALIGN'edness!
1799         } else if (static_cast<int>(row->width()) < workWidth(*bview)) {
1800                 // is it block, flushleft or flushright?
1801                 // set x how you need it
1802                 int align;
1803                 if (row->par()->params().align() == LYX_ALIGN_LAYOUT) {
1804                         align = layout->align;
1805                 } else {
1806                         align = row->par()->params().align();
1807                 }
1808
1809                 // center displayed insets
1810                 Inset * inset;
1811                 if (row->par()->isInset(row->pos())
1812                     && (inset=row->par()->getInset(row->pos()))
1813                     && (inset->display())) // || (inset->scroll() < 0)))
1814                     align = (inset->lyxCode() == Inset::MATHMACRO_CODE)
1815                         ? LYX_ALIGN_BLOCK : LYX_ALIGN_CENTER;
1816                 // ERT insets should always be LEFT ALIGNED on screen
1817                 inset = row->par()->inInset();
1818                 if (inset && inset->owner() &&
1819                         inset->owner()->lyxCode() == Inset::ERT_CODE)
1820                 {
1821                         align = LYX_ALIGN_LEFT;
1822                 }
1823
1824                 switch (align) {
1825             case LYX_ALIGN_BLOCK:
1826                         ns = row->numberOfSeparators();
1827                         if (ns && row->next() && row->next()->par() == row->par() &&
1828                             !(row->next()->par()->isNewline(row->next()->pos() - 1))
1829                             && !(row->next()->par()->isInset(row->next()->pos())
1830                                  && row->next()->par()->getInset(row->next()->pos())
1831                                  && row->next()->par()->getInset(row->next()->pos())->display())
1832                                 )
1833                         {
1834                                 fill_separator = w / ns;
1835                         } else if (is_rtl) {
1836                                 x += w;
1837                         }
1838                         break;
1839             case LYX_ALIGN_RIGHT:
1840                         x += w;
1841                         break;
1842             case LYX_ALIGN_CENTER:
1843                         x += w / 2;
1844                         break;
1845                 }
1846         }
1847         if (!bidi)
1848                 return;
1849
1850         computeBidiTables(bview->buffer(), row);
1851         if (is_rtl) {
1852                 pos_type body_pos = row->par()->beginningOfBody();
1853                 pos_type last = row->lastPos();
1854
1855                 if (body_pos > 0 &&
1856                     (body_pos - 1 > last ||
1857                      !row->par()->isLineSeparator(body_pos - 1))) {
1858                         x += font_metrics::width(layout->labelsep,
1859                                             getLabelFont(bview->buffer(), row->par()));
1860                         if (body_pos - 1 <= last)
1861                                 x += fill_label_hfill;
1862                 }
1863         }
1864 }
1865
1866
1867 // important for the screen
1868
1869
1870 // the cursor set functions have a special mechanism. When they
1871 // realize, that you left an empty paragraph, they will delete it.
1872 // They also delete the corresponding row
1873
1874 void LyXText::cursorRightOneWord(BufferView * bview) const
1875 {
1876         // treat floats, HFills and Insets as words
1877         LyXCursor tmpcursor = cursor;
1878         // CHECK See comment on top of text.C
1879
1880         if (tmpcursor.pos() == tmpcursor.par()->size()
1881             && tmpcursor.par()->next()) {
1882                         tmpcursor.par(tmpcursor.par()->next());
1883                         tmpcursor.pos(0);
1884         } else {
1885                 int steps = 0;
1886
1887                 // Skip through initial nonword stuff.
1888                 while (tmpcursor.pos() < tmpcursor.par()->size() &&
1889                        ! tmpcursor.par()->isWord(tmpcursor.pos())) {
1890                   //    printf("Current pos1 %d", tmpcursor.pos()) ;
1891                         tmpcursor.pos(tmpcursor.pos() + 1);
1892                         ++steps;
1893                 }
1894                 // Advance through word.
1895                 while (tmpcursor.pos() < tmpcursor.par()->size() &&
1896                         tmpcursor.par()->isWord(tmpcursor.pos())) {
1897                   //     printf("Current pos2 %d", tmpcursor.pos()) ;
1898                         tmpcursor.pos(tmpcursor.pos() + 1);
1899                         ++steps;
1900                 }
1901         }
1902         setCursor(bview, tmpcursor.par(), tmpcursor.pos());
1903 }
1904
1905
1906 void LyXText::cursorTab(BufferView * bview) const
1907 {
1908         LyXCursor tmpcursor = cursor;
1909         while (tmpcursor.pos() < tmpcursor.par()->size()
1910            && !tmpcursor.par()->isNewline(tmpcursor.pos()))
1911         tmpcursor.pos(tmpcursor.pos() + 1);
1912
1913         if (tmpcursor.pos() == tmpcursor.par()->size()) {
1914                 if (tmpcursor.par()->next()) {
1915                         tmpcursor.par(tmpcursor.par()->next());
1916                         tmpcursor.pos(0);
1917                 }
1918         } else
1919                 tmpcursor.pos(tmpcursor.pos() + 1);
1920         setCursor(bview, tmpcursor.par(), tmpcursor.pos());
1921 }
1922
1923
1924 // Skip initial whitespace at end of word and move cursor to *start*
1925 // of prior word, not to end of next prior word.
1926 void LyXText::cursorLeftOneWord(BufferView * bview)  const
1927 {
1928         LyXCursor tmpcursor = cursor;
1929         cursorLeftOneWord(tmpcursor);
1930         setCursor(bview, tmpcursor.par(), tmpcursor.pos());
1931 }
1932
1933
1934 void LyXText::cursorLeftOneWord(LyXCursor & cur) const
1935 {
1936         // treat HFills, floats and Insets as words
1937         cur = cursor;
1938         while (cur.pos()
1939                && (cur.par()->isSeparator(cur.pos() - 1)
1940                    || cur.par()->isKomma(cur.pos() - 1))
1941                && !(cur.par()->isHfill(cur.pos() - 1)
1942                     || cur.par()->isInset(cur.pos() - 1)))
1943                 cur.pos(cur.pos() - 1);
1944
1945         if (cur.pos()
1946             && (cur.par()->isInset(cur.pos() - 1)
1947                 || cur.par()->isHfill(cur.pos() - 1))) {
1948                 cur.pos(cur.pos() - 1);
1949         } else if (!cur.pos()) {
1950                 if (cur.par()->previous()) {
1951                         cur.par(cur.par()->previous());
1952                         cur.pos(cur.par()->size());
1953                 }
1954         } else {                // Here, cur != 0
1955                 while (cur.pos() > 0 &&
1956                        cur.par()->isWord(cur.pos() - 1))
1957                         cur.pos(cur.pos() - 1);
1958         }
1959 }
1960
1961
1962 // Select current word. This depends on behaviour of
1963 // CursorLeftOneWord(), so it is patched as well.
1964 void LyXText::getWord(LyXCursor & from, LyXCursor & to,
1965                       word_location const loc) const
1966 {
1967         // first put the cursor where we wana start to select the word
1968         from = cursor;
1969         switch (loc) {
1970         case WHOLE_WORD_STRICT:
1971                 if (cursor.pos() == 0 || cursor.pos() == cursor.par()->size()
1972                     || cursor.par()->isSeparator(cursor.pos())
1973                     || cursor.par()->isKomma(cursor.pos())
1974                     || cursor.par()->isSeparator(cursor.pos() - 1)
1975                     || cursor.par()->isKomma(cursor.pos() - 1)) {
1976                         to = from;
1977                         return;
1978                 }
1979                 // no break here, we go to the next
1980
1981         case WHOLE_WORD:
1982                 // Move cursor to the beginning, when not already there.
1983                 if (from.pos() && !from.par()->isSeparator(from.pos() - 1)
1984                     && !from.par()->isKomma(from.pos() - 1))
1985                         cursorLeftOneWord(from);
1986                 break;
1987         case PREVIOUS_WORD:
1988                 // always move the cursor to the beginning of previous word
1989                 cursorLeftOneWord(from);
1990                 break;
1991         case NEXT_WORD:
1992                 lyxerr << "LyXText::getWord: NEXT_WORD not implemented yet\n";
1993                 break;
1994         case PARTIAL_WORD:
1995                 break;
1996         }
1997         to = from;
1998         while (to.pos() < to.par()->size()
1999                && !to.par()->isSeparator(to.pos())
2000                && !to.par()->isKomma(to.pos())
2001                && !to.par()->isHfill(to.pos())
2002                && !to.par()->isInset(to.pos()))
2003         {
2004                 to.pos(to.pos() + 1);
2005         }
2006 }
2007
2008
2009 void LyXText::selectWord(BufferView * bview, word_location const loc)
2010 {
2011         LyXCursor from;
2012         LyXCursor to;
2013         getWord(from, to, loc);
2014         if (cursor != from)
2015                 setCursor(bview, from.par(), from.pos());
2016         if (to == from)
2017                 return;
2018         selection.cursor = cursor;
2019         setCursor(bview, to.par(), to.pos());
2020         setSelection(bview);
2021 }
2022
2023
2024 // Select the word currently under the cursor when no
2025 // selection is currently set
2026 bool LyXText::selectWordWhenUnderCursor(BufferView * bview,
2027                                         word_location const loc)
2028 {
2029         if (!selection.set()) {
2030                 selectWord(bview, loc);
2031                 return selection.set();
2032         }
2033         return false;
2034 }
2035
2036
2037 void LyXText::acceptChange(BufferView * bv)
2038 {
2039         if (!selection.set() && cursor.par()->size())
2040                 return;
2041
2042         bv->hideCursor();
2043
2044         if (selection.start.par() == selection.end.par()) {
2045                 LyXCursor & startc = selection.start;
2046                 LyXCursor & endc = selection.end;
2047                 setUndo(bv, Undo::INSERT, startc.par(), startc.par()->next());
2048                 startc.par()->acceptChange(startc.pos(), endc.pos());
2049                 finishUndo();
2050                 clearSelection();
2051                 redoParagraphs(bv, startc, startc.par()->next());
2052                 setCursorIntern(bv, startc.par(), 0);
2053         }
2054 #warning handle multi par selection
2055 }
2056
2057
2058 void LyXText::rejectChange(BufferView * bv)
2059 {
2060         if (!selection.set() && cursor.par()->size())
2061                 return;
2062
2063         bv->hideCursor();
2064
2065         if (selection.start.par() == selection.end.par()) {
2066                 LyXCursor & startc = selection.start;
2067                 LyXCursor & endc = selection.end;
2068                 setUndo(bv, Undo::INSERT, startc.par(), startc.par()->next());
2069                 startc.par()->rejectChange(startc.pos(), endc.pos());
2070                 finishUndo();
2071                 clearSelection();
2072                 redoParagraphs(bv, startc, startc.par()->next());
2073                 setCursorIntern(bv, startc.par(), 0);
2074         }
2075 #warning handle multi par selection
2076 }
2077
2078
2079 // This function is only used by the spellchecker for NextWord().
2080 // It doesn't handle LYX_ACCENTs and probably never will.
2081 WordLangTuple const
2082 LyXText::selectNextWordToSpellcheck(BufferView * bview, float & value) const
2083 {
2084         if (the_locking_inset) {
2085                 WordLangTuple word = the_locking_inset->selectNextWordToSpellcheck(bview, value);
2086                 if (!word.word().empty()) {
2087                         value += float(cursor.y());
2088                         value /= float(height);
2089                         return word;
2090                 }
2091                 // we have to go on checking so move cursor to the next char
2092                 if (cursor.pos() == cursor.par()->size()) {
2093                         if (!cursor.par()->next())
2094                                 return word;
2095                         cursor.par(cursor.par()->next());
2096                         cursor.pos(0);
2097                 } else
2098                         cursor.pos(cursor.pos() + 1);
2099         }
2100         Paragraph * tmppar = cursor.par();
2101
2102         // If this is not the very first word, skip rest of
2103         // current word because we are probably in the middle
2104         // of a word if there is text here.
2105         if (cursor.pos() || cursor.par()->previous()) {
2106                 while (cursor.pos() < cursor.par()->size()
2107                        && cursor.par()->isLetter(cursor.pos()))
2108                         cursor.pos(cursor.pos() + 1);
2109         }
2110
2111         // Now, skip until we have real text (will jump paragraphs)
2112         while (1) {
2113                 Paragraph * cpar(cursor.par());
2114                 pos_type const cpos(cursor.pos());
2115
2116                 if (cpos == cpar->size()) {
2117                         if (cpar->next()) {
2118                                 cursor.par(cpar->next());
2119                                 cursor.pos(0);
2120                                 continue;
2121                         }
2122                         break;
2123                 }
2124
2125                 bool const is_bad_inset(cpar->isInset(cpos)
2126                         && !cpar->getInset(cpos)->allowSpellcheck());
2127
2128                 if (cpar->isLetter(cpos) && !isDeletedText(*cpar, cpos)
2129                         && !is_bad_inset)
2130                         break;
2131
2132                 cursor.pos(cpos + 1);
2133         }
2134
2135         // now check if we hit an inset so it has to be a inset containing text!
2136         if (cursor.pos() < cursor.par()->size() &&
2137             cursor.par()->isInset(cursor.pos())) {
2138                 // lock the inset!
2139                 cursor.par()->getInset(cursor.pos())->edit(bview);
2140                 // now call us again to do the above trick
2141                 // but obviously we have to start from down below ;)
2142                 return bview->text->selectNextWordToSpellcheck(bview, value);
2143         }
2144
2145         // Update the value if we changed paragraphs
2146         if (cursor.par() != tmppar) {
2147                 setCursor(bview, cursor.par(), cursor.pos());
2148                 value = float(cursor.y())/float(height);
2149         }
2150
2151         // Start the selection from here
2152         selection.cursor = cursor;
2153
2154         string lang_code(
2155                 getFont(bview->buffer(), cursor.par(), cursor.pos())
2156                         .language()->code());
2157         // and find the end of the word (insets like optional hyphens
2158         // and ligature break are part of a word)
2159         while (cursor.pos() < cursor.par()->size()
2160                && cursor.par()->isLetter(cursor.pos())
2161                && !isDeletedText(*cursor.par(), cursor.pos()))
2162                 cursor.pos(cursor.pos() + 1);
2163
2164         // Finally, we copy the word to a string and return it
2165         string str;
2166         if (selection.cursor.pos() < cursor.pos()) {
2167                 pos_type i;
2168                 for (i = selection.cursor.pos(); i < cursor.pos(); ++i) {
2169                         if (!cursor.par()->isInset(i))
2170                                 str += cursor.par()->getChar(i);
2171                 }
2172         }
2173         return WordLangTuple(str, lang_code);
2174 }
2175
2176
2177 // This one is also only for the spellchecker
2178 void LyXText::selectSelectedWord(BufferView * bview)
2179 {
2180         if (the_locking_inset) {
2181                 the_locking_inset->selectSelectedWord(bview);
2182                 return;
2183         }
2184         // move cursor to the beginning
2185         setCursor(bview, selection.cursor.par(), selection.cursor.pos());
2186
2187         // set the sel cursor
2188         selection.cursor = cursor;
2189
2190         // now find the end of the word
2191         while (cursor.pos() < cursor.par()->size()
2192                && (cursor.par()->isLetter(cursor.pos())))
2193                 cursor.pos(cursor.pos() + 1);
2194
2195         setCursor(bview, cursor.par(), cursor.pos());
2196
2197         // finally set the selection
2198         setSelection(bview);
2199 }
2200
2201
2202 // Delete from cursor up to the end of the current or next word.
2203 void LyXText::deleteWordForward(BufferView * bview)
2204 {
2205         if (cursor.par()->empty())
2206                 cursorRight(bview);
2207         else {
2208                 LyXCursor tmpcursor = cursor;
2209                 tmpcursor.row(0); // ??
2210                 selection.set(true); // to avoid deletion
2211                 cursorRightOneWord(bview);
2212                 setCursor(bview, tmpcursor, tmpcursor.par(), tmpcursor.pos());
2213                 selection.cursor = cursor;
2214                 cursor = tmpcursor;
2215                 setSelection(bview);
2216
2217                 // Great, CutSelection() gets rid of multiple spaces.
2218                 cutSelection(bview, true, false);
2219         }
2220 }
2221
2222
2223 // Delete from cursor to start of current or prior word.
2224 void LyXText::deleteWordBackward(BufferView * bview)
2225 {
2226         if (cursor.par()->empty())
2227                 cursorLeft(bview);
2228         else {
2229                 LyXCursor tmpcursor = cursor;
2230                 tmpcursor.row(0); // ??
2231                 selection.set(true); // to avoid deletion
2232                 cursorLeftOneWord(bview);
2233                 setCursor(bview, tmpcursor, tmpcursor.par(), tmpcursor.pos());
2234                 selection.cursor = cursor;
2235                 cursor = tmpcursor;
2236                 setSelection(bview);
2237                 cutSelection(bview, true, false);
2238         }
2239 }
2240
2241
2242 // Kill to end of line.
2243 void LyXText::deleteLineForward(BufferView * bview)
2244 {
2245         if (cursor.par()->empty())
2246                 // Paragraph is empty, so we just go to the right
2247                 cursorRight(bview);
2248         else {
2249                 LyXCursor tmpcursor = cursor;
2250                 // We can't store the row over a regular setCursor
2251                 // so we set it to 0 and reset it afterwards.
2252                 tmpcursor.row(0); // ??
2253                 selection.set(true); // to avoid deletion
2254                 cursorEnd(bview);
2255                 setCursor(bview, tmpcursor, tmpcursor.par(), tmpcursor.pos());
2256                 selection.cursor = cursor;
2257                 cursor = tmpcursor;
2258                 setSelection(bview);
2259                 // What is this test for ??? (JMarc)
2260                 if (!selection.set()) {
2261                         deleteWordForward(bview);
2262                 } else {
2263                         cutSelection(bview, true, false);
2264                 }
2265         }
2266 }
2267
2268
2269 void LyXText::changeCase(BufferView & bview, LyXText::TextCase action)
2270 {
2271         LyXCursor from;
2272         LyXCursor to;
2273
2274         if (selection.set()) {
2275                 from = selection.start;
2276                 to = selection.end;
2277         } else {
2278                 getWord(from, to, PARTIAL_WORD);
2279                 setCursor(&bview, to.par(), to.pos() + 1);
2280         }
2281
2282         lyx::Assert(from <= to);
2283
2284         setUndo(&bview, Undo::FINISH, from.par(), to.par()->next());
2285
2286         pos_type pos = from.pos();
2287         Paragraph * par = from.par();
2288
2289         while (par && (pos != to.pos() || par != to.par())) {
2290                 if (pos == par->size()) {
2291                         par = par->next();
2292                         pos = 0;
2293                         continue;
2294                 }
2295                 unsigned char c = par->getChar(pos);
2296                 if (!IsInsetChar(c) && !IsHfillChar(c)) {
2297                         switch (action) {
2298                         case text_lowercase:
2299                                 c = lowercase(c);
2300                                 break;
2301                         case text_capitalization:
2302                                 c = uppercase(c);
2303                                 action = text_lowercase;
2304                                 break;
2305                         case text_uppercase:
2306                                 c = uppercase(c);
2307                                 break;
2308                         }
2309                 }
2310 #warning changes
2311                 par->setChar(pos, c);
2312                 checkParagraph(&bview, par, pos);
2313
2314                 ++pos;
2315         }
2316         if (to.row() != from.row()) {
2317                 refresh_y = from.y() - from.row()->baseline();
2318                 refresh_row = from.row();
2319                 status(&bview, LyXText::NEED_MORE_REFRESH);
2320         }
2321 }
2322
2323
2324 void LyXText::transposeChars(BufferView & bview)
2325 {
2326         Paragraph * tmppar = cursor.par();
2327
2328         setUndo(&bview, Undo::FINISH, tmppar, tmppar->next());
2329
2330         pos_type tmppos = cursor.pos();
2331
2332         // First decide if it is possible to transpose at all
2333
2334         if (tmppos == 0 || tmppos == tmppar->size())
2335                 return;
2336
2337         if (isDeletedText(*tmppar, tmppos - 1)
2338                 || isDeletedText(*tmppar, tmppos))
2339                 return;
2340
2341         unsigned char c1 = tmppar->getChar(tmppos);
2342         unsigned char c2 = tmppar->getChar(tmppos - 1);
2343
2344         // We should have an implementation that handles insets
2345         // as well, but that will have to come later. (Lgb)
2346         if (c1 == Paragraph::META_INSET || c2 == Paragraph::META_INSET)
2347                 return;
2348
2349         bool const erased = tmppar->erase(tmppos - 1, tmppos + 1);
2350         pos_type const ipos(erased ? tmppos - 1 : tmppos + 1);
2351
2352         tmppar->insertChar(ipos, c1);
2353         tmppar->insertChar(ipos + 1, c2);
2354
2355         checkParagraph(&bview, tmppar, tmppos);
2356 }
2357
2358
2359 void LyXText::Delete(BufferView * bview)
2360 {
2361         // this is a very easy implementation
2362
2363         LyXCursor old_cursor = cursor;
2364         int const old_cur_par_id = old_cursor.par()->id();
2365         int const old_cur_par_prev_id = old_cursor.par()->previous() ?
2366                 old_cursor.par()->previous()->id() : -1;
2367
2368         // just move to the right
2369         cursorRight(bview);
2370
2371         // CHECK Look at the comment here.
2372         // This check is not very good...
2373         // The cursorRightIntern calls DeleteEmptyParagrapgMechanism
2374         // and that can very well delete the par or par->previous in
2375         // old_cursor. Will a solution where we compare paragraph id's
2376         //work better?
2377         if ((cursor.par()->previous() ? cursor.par()->previous()->id() : -1)
2378             == old_cur_par_prev_id
2379             && cursor.par()->id() != old_cur_par_id) {
2380                 // delete-empty-paragraph-mechanism has done it
2381                 return;
2382         }
2383
2384         // if you had success make a backspace
2385         if (old_cursor.par() != cursor.par() || old_cursor.pos() != cursor.pos()) {
2386                 LyXCursor tmpcursor = cursor;
2387                 // to make sure undo gets the right cursor position
2388                 cursor = old_cursor;
2389                 setUndo(bview, Undo::DELETE,
2390                         cursor.par(), cursor.par()->next());
2391                 cursor = tmpcursor;
2392                 backspace(bview);
2393         }
2394 }
2395
2396
2397 void LyXText::backspace(BufferView * bview)
2398 {
2399         // Get the font that is used to calculate the baselineskip
2400         pos_type lastpos = cursor.par()->size();
2401         LyXFont rawparfont =
2402                 cursor.par()->getFontSettings(bview->buffer()->params,
2403                                               lastpos - 1);
2404
2405         if (cursor.pos() == 0) {
2406                 // The cursor is at the beginning of a paragraph,
2407                 // so the the backspace will collapse two paragraphs into one.
2408
2409                 // but it's not allowed unless it's new
2410                 if (cursor.par()->isChangeEdited(0, cursor.par()->size()))
2411                         return;
2412
2413                 // we may paste some paragraphs
2414
2415                 // is it an empty paragraph?
2416
2417                 if ((lastpos == 0
2418                      || (lastpos == 1 && cursor.par()->isSeparator(0)))) {
2419                         // This is an empty paragraph and we delete it just by moving the cursor one step
2420                         // left and let the DeleteEmptyParagraphMechanism handle the actual deletion
2421                         // of the paragraph.
2422
2423                         if (cursor.par()->previous()) {
2424                                 Paragraph * tmppar = cursor.par()->previous();
2425                                 if (cursor.par()->layout() == tmppar->layout()
2426                                     && cursor.par()->getAlign() == tmppar->getAlign()) {
2427                                         // Inherit bottom DTD from the paragraph below.
2428                                         // (the one we are deleting)
2429                                         tmppar->params().lineBottom(cursor.par()->params().lineBottom());
2430                                         tmppar->params().spaceBottom(cursor.par()->params().spaceBottom());
2431                                         tmppar->params().pagebreakBottom(cursor.par()->params().pagebreakBottom());
2432                                 }
2433
2434                                 cursorLeft(bview);
2435
2436                                 // the layout things can change the height of a row !
2437                                 int const tmpheight = cursor.row()->height();
2438                                 setHeightOfRow(bview, cursor.row());
2439                                 if (cursor.row()->height() != tmpheight) {
2440                                         refresh_y = cursor.y() - cursor.row()->baseline();
2441                                         refresh_row = cursor.row();
2442                                         status(bview, LyXText::NEED_MORE_REFRESH);
2443                                 }
2444                                 return;
2445                         }
2446                 }
2447
2448                 if (cursor.par()->previous()) {
2449                         setUndo(bview, Undo::DELETE,
2450                                 cursor.par()->previous(), cursor.par()->next());
2451                 }
2452
2453                 Paragraph * tmppar = cursor.par();
2454                 Row * tmprow = cursor.row();
2455
2456                 // We used to do cursorLeftIntern() here, but it is
2457                 // not a good idea since it triggers the auto-delete
2458                 // mechanism. So we do a cursorLeftIntern()-lite,
2459                 // without the dreaded mechanism. (JMarc)
2460                 if (cursor.par()->previous()) {
2461                         // steps into the above paragraph.
2462                         setCursorIntern(bview, cursor.par()->previous(),
2463                                         cursor.par()->previous()->size(),
2464                                         false);
2465                 }
2466
2467                 // Pasting is not allowed, if the paragraphs have different
2468                 // layout. I think it is a real bug of all other
2469                 // word processors to allow it. It confuses the user.
2470                 // Even so with a footnote paragraph and a non-footnote
2471                 // paragraph. I will not allow pasting in this case,
2472                 // because the user would be confused if the footnote behaves
2473                 // different wether it is open or closed.
2474
2475                 //      Correction: Pasting is always allowed with standard-layout
2476                 LyXTextClass const & tclass =
2477                         bview->buffer()->params.getLyXTextClass();
2478
2479                 if (cursor.par() != tmppar
2480                     && (cursor.par()->layout() == tmppar->layout()
2481                         || tmppar->layout() == tclass.defaultLayout())
2482                     && cursor.par()->getAlign() == tmppar->getAlign()) {
2483                         removeParagraph(tmprow);
2484                         removeRow(tmprow);
2485                         mergeParagraph(bview->buffer()->params, bview->buffer()->paragraphs, cursor.par());
2486
2487                         if (!cursor.pos() || !cursor.par()->isSeparator(cursor.pos() - 1))
2488                                 ; //cursor.par()->insertChar(cursor.pos(), ' ');
2489                         // strangely enough it seems that commenting out the line above removes
2490                         // most or all of the segfaults. I will however also try to move the
2491                         // two Remove... lines in front of the PasteParagraph too.
2492                         else
2493                                 if (cursor.pos())
2494                                         cursor.pos(cursor.pos() - 1);
2495
2496                         status(bview, LyXText::NEED_MORE_REFRESH);
2497                         refresh_row = cursor.row();
2498                         refresh_y = cursor.y() - cursor.row()->baseline();
2499
2500                         // remove the lost paragraph
2501                         // This one is not safe, since the paragraph that the tmprow and the
2502                         // following rows belong to has been deleted by the PasteParagraph
2503                         // above. The question is... could this be moved in front of the
2504                         // PasteParagraph?
2505                         //RemoveParagraph(tmprow);
2506                         //RemoveRow(tmprow);
2507
2508                         // This rebuilds the rows.
2509                         appendParagraph(bview, cursor.row());
2510                         updateCounters(bview);
2511
2512                         // the row may have changed, block, hfills etc.
2513                         setCursor(bview, cursor.par(), cursor.pos(), false);
2514                 }
2515         } else {
2516                 // this is the code for a normal backspace, not pasting
2517                 // any paragraphs
2518                 setUndo(bview, Undo::DELETE,
2519                         cursor.par(), cursor.par()->next());
2520                 // We used to do cursorLeftIntern() here, but it is
2521                 // not a good idea since it triggers the auto-delete
2522                 // mechanism. So we do a cursorLeftIntern()-lite,
2523                 // without the dreaded mechanism. (JMarc)
2524                 setCursorIntern(bview, cursor.par(), cursor.pos()- 1,
2525                                 false, cursor.boundary());
2526
2527                 if (cursor.par()->isInset(cursor.pos())) {
2528                         // force complete redo when erasing display insets
2529                         // this is a cruel method but safe..... Matthias
2530                         if (cursor.par()->getInset(cursor.pos())->display() ||
2531                             cursor.par()->getInset(cursor.pos())->needFullRow()) {
2532                                 cursor.par()->erase(cursor.pos());
2533                                 redoParagraph(bview);
2534                                 return;
2535                         }
2536                 }
2537
2538                 Row * row = cursor.row();
2539                 int y = cursor.y() - row->baseline();
2540                 pos_type z;
2541                 // remember that a space at the end of a row doesnt count
2542                 // when calculating the fill
2543                 if (cursor.pos() < row->lastPos() ||
2544                     !cursor.par()->isLineSeparator(cursor.pos())) {
2545                         row->fill(row->fill() + singleWidth(bview,
2546                                                             cursor.par(),
2547                                                             cursor.pos()));
2548                 }
2549
2550                 // some special code when deleting a newline. This is similar
2551                 // to the behavior when pasting paragraphs
2552                 if (cursor.pos() && cursor.par()->isNewline(cursor.pos())) {
2553                         cursor.par()->erase(cursor.pos());
2554                         // refresh the positions
2555                         Row * tmprow = row;
2556                         while (tmprow->next() && tmprow->next()->par() == row->par()) {
2557                                 tmprow = tmprow->next();
2558                                 tmprow->pos(tmprow->pos() - 1);
2559                         }
2560                         if (cursor.par()->isLineSeparator(cursor.pos() - 1))
2561                                 cursor.pos(cursor.pos() - 1);
2562
2563                         if (cursor.pos() < cursor.par()->size()
2564                             && !cursor.par()->isSeparator(cursor.pos())) {
2565                                 cursor.par()->insertChar(cursor.pos(), ' ');
2566                                 setCharFont(bview->buffer(), cursor.par(),
2567                                             cursor.pos(), current_font);
2568                                 // refresh the positions
2569                                 tmprow = row;
2570                                 while (tmprow->next() && tmprow->next()->par() == row->par()) {
2571                                         tmprow = tmprow->next();
2572                                         tmprow->pos(tmprow->pos() + 1);
2573                                 }
2574                         }
2575                 } else {
2576                         cursor.par()->erase(cursor.pos());
2577
2578                         // refresh the positions
2579                         Row * tmprow = row;
2580                         while (tmprow->next()
2581                                && tmprow->next()->par() == row->par()) {
2582                                 tmprow = tmprow->next();
2583                                 tmprow->pos(tmprow->pos() - 1);
2584                         }
2585
2586                         // delete newlines at the beginning of paragraphs
2587                         while (!cursor.par()->empty() &&
2588                                cursor.par()->isNewline(cursor.pos()) &&
2589                                cursor.pos() == cursor.par()->beginningOfBody()) {
2590                                 cursor.par()->erase(cursor.pos());
2591                                 // refresh the positions
2592                                 tmprow = row;
2593                                 while (tmprow->next() &&
2594                                        tmprow->next()->par() == row->par()) {
2595                                         tmprow = tmprow->next();
2596                                         tmprow->pos(tmprow->pos() - 1);
2597                                 }
2598                         }
2599                 }
2600
2601                 // is there a break one row above
2602                 if (row->previous() && row->previous()->par() == row->par()) {
2603                         z = nextBreakPoint(bview, row->previous(),
2604                                            workWidth(*bview));
2605                         if (z >= row->pos()) {
2606                                 row->pos(z + 1);
2607
2608                                 Row * tmprow = row->previous();
2609
2610                                 // maybe the current row is now empty
2611                                 if (row->pos() >= row->par()->size()) {
2612                                         // remove it
2613                                         removeRow(row);
2614                                         need_break_row = 0;
2615                                 } else {
2616                                         breakAgainOneRow(bview, row);
2617                                         if (row->next() && row->next()->par() == row->par())
2618                                                 need_break_row = row->next();
2619                                         else
2620                                                 need_break_row = 0;
2621                                 }
2622
2623                                 // set the dimensions of the row above
2624                                 y -= tmprow->height();
2625                                 tmprow->fill(fill(*bview, *tmprow, workWidth(*bview)));
2626                                 setHeightOfRow(bview, tmprow);
2627
2628                                 refresh_y = y;
2629                                 refresh_row = tmprow;
2630                                 status(bview, LyXText::NEED_MORE_REFRESH);
2631                                 setCursor(bview, cursor.par(), cursor.pos(),
2632                                           false, cursor.boundary());
2633                                 //current_font = rawtmpfont;
2634                                 //real_current_font = realtmpfont;
2635                                 // check, whether the last character's font has changed.
2636                                 if (rawparfont !=
2637                                     cursor.par()->getFontSettings(bview->buffer()->params,
2638                                                                   cursor.par()->size() - 1))
2639                                         redoHeightOfParagraph(bview, cursor);
2640                                 return;
2641                         }
2642                 }
2643
2644                 // break the cursor row again
2645                 if (row->next() && row->next()->par() == row->par() &&
2646                     (row->lastPos() == row->par()->size() - 1 ||
2647                      nextBreakPoint(bview, row, workWidth(*bview)) != row->lastPos())) {
2648
2649                         // it can happen that a paragraph loses one row
2650                         // without a real breakup. This is when a word
2651                         // is to long to be broken. Well, I don t care this
2652                         // hack ;-)
2653                         if (row->lastPos() == row->par()->size() - 1)
2654                                 removeRow(row->next());
2655
2656                         refresh_y = y;
2657                         refresh_row = row;
2658                         status(bview, LyXText::NEED_MORE_REFRESH);
2659
2660                         breakAgainOneRow(bview, row);
2661                         // will the cursor be in another row now?
2662                         if (row->next() && row->next()->par() == row->par() &&
2663                             row->lastPos() <= cursor.pos()) {
2664                                 row = row->next();
2665                                 breakAgainOneRow(bview, row);
2666                         }
2667
2668                         setCursor(bview, cursor.par(), cursor.pos(), false, cursor.boundary());
2669
2670                         if (row->next() && row->next()->par() == row->par())
2671                                 need_break_row = row->next();
2672                         else
2673                                 need_break_row = 0;
2674                 } else  {
2675                         // set the dimensions of the row
2676                         row->fill(fill(*bview, *row, workWidth(*bview)));
2677                         int const tmpheight = row->height();
2678                         setHeightOfRow(bview, row);
2679                         if (tmpheight == row->height())
2680                                 status(bview, LyXText::NEED_VERY_LITTLE_REFRESH);
2681                         else
2682                                 status(bview, LyXText::NEED_MORE_REFRESH);
2683                         refresh_y = y;
2684                         refresh_row = row;
2685                         setCursor(bview, cursor.par(), cursor.pos(), false, cursor.boundary());
2686                 }
2687         }
2688
2689         // current_font = rawtmpfont;
2690         // real_current_font = realtmpfont;
2691
2692         if (isBoundary(bview->buffer(), cursor.par(), cursor.pos())
2693             != cursor.boundary())
2694                 setCursor(bview, cursor.par(), cursor.pos(), false,
2695                           !cursor.boundary());
2696
2697         lastpos = cursor.par()->size();
2698         if (cursor.pos() == lastpos)
2699                 setCurrentFont(bview);
2700
2701         // check, whether the last characters font has changed.
2702         if (rawparfont !=
2703             cursor.par()->getFontSettings(bview->buffer()->params, lastpos - 1)) {
2704                 redoHeightOfParagraph(bview, cursor);
2705         } else {
2706                 // now the special right address boxes
2707                 if (cursor.par()->layout()->margintype
2708                     == MARGIN_RIGHT_ADDRESS_BOX) {
2709                         redoDrawingOfParagraph(bview, cursor);
2710                 }
2711         }
2712 }
2713
2714
2715 // returns the column near the specified x-coordinate of the row
2716 // x is set to the real beginning of this column
2717 pos_type
2718 LyXText::getColumnNearX(BufferView * bview, Row * row, int & x,
2719                         bool & boundary) const
2720 {
2721         float tmpx = 0.0;
2722         float fill_separator;
2723         float fill_hfill;
2724         float fill_label_hfill;
2725
2726         prepareToPrint(bview, row, tmpx, fill_separator,
2727                        fill_hfill, fill_label_hfill);
2728
2729         pos_type vc = row->pos();
2730         pos_type last = row->lastPrintablePos();
2731         pos_type c = 0;
2732
2733         LyXLayout_ptr const & layout = row->par()->layout();
2734
2735         bool left_side = false;
2736
2737         pos_type body_pos = row->par()->beginningOfBody();
2738         float last_tmpx = tmpx;
2739
2740         if (body_pos > 0 &&
2741             (body_pos - 1 > last ||
2742              !row->par()->isLineSeparator(body_pos - 1)))
2743                 body_pos = 0;
2744
2745         // check for empty row
2746         if (!row->par()->size()) {
2747                 x = int(tmpx);
2748                 return 0;
2749         }
2750
2751         while (vc <= last && tmpx <= x) {
2752                 c = vis2log(vc);
2753                 last_tmpx = tmpx;
2754                 if (body_pos > 0 && c == body_pos-1) {
2755                         tmpx += fill_label_hfill +
2756                                 font_metrics::width(layout->labelsep,
2757                                                getLabelFont(bview->buffer(), row->par()));
2758                         if (row->par()->isLineSeparator(body_pos - 1))
2759                                 tmpx -= singleWidth(bview, row->par(), body_pos-1);
2760                 }
2761
2762                 if (row->hfillExpansion(c)) {
2763                         tmpx += singleWidth(bview, row->par(), c);
2764                         if (c >= body_pos)
2765                                 tmpx += fill_hfill;
2766                         else
2767                                 tmpx += fill_label_hfill;
2768                 } else if (row->par()->isSeparator(c)) {
2769                         tmpx += singleWidth(bview, row->par(), c);
2770                         if (c >= body_pos)
2771                                 tmpx+= fill_separator;
2772                 } else {
2773                         tmpx += singleWidth(bview, row->par(), c);
2774                 }
2775                 ++vc;
2776         }
2777
2778         if ((tmpx + last_tmpx) / 2 > x) {
2779                 tmpx = last_tmpx;
2780                 left_side = true;
2781         }
2782
2783         if (vc > last + 1)  // This shouldn't happen.
2784                 vc = last + 1;
2785
2786         boundary = false;
2787         bool const lastrow = lyxrc.rtl_support // This is not needed, but gives
2788                                          // some speedup if rtl_support=false
2789                 && (!row->next() || row->next()->par() != row->par());
2790         bool const rtl = (lastrow)
2791                 ? row->par()->isRightToLeftPar(bview->buffer()->params)
2792                 : false; // If lastrow is false, we don't need to compute
2793                          // the value of rtl.
2794
2795         if (lastrow &&
2796                  ((rtl &&  left_side && vc == row->pos() && x < tmpx - 5) ||
2797                    (!rtl && !left_side && vc == last + 1   && x > tmpx + 5)))
2798                 c = last + 1;
2799         else if (vc == row->pos()) {
2800                 c = vis2log(vc);
2801                 if (bidi_level(c) % 2 == 1)
2802                         ++c;
2803         } else {
2804                 c = vis2log(vc - 1);
2805                 bool const rtl = (bidi_level(c) % 2 == 1);
2806                 if (left_side == rtl) {
2807                         ++c;
2808                         boundary = isBoundary(bview->buffer(), row->par(), c);
2809                 }
2810         }
2811
2812         if (row->pos() <= last && c > last
2813             && row->par()->isNewline(last)) {
2814                 if (bidi_level(last) % 2 == 0)
2815                         tmpx -= singleWidth(bview, row->par(), last);
2816                 else
2817                         tmpx += singleWidth(bview, row->par(), last);
2818                 c = last;
2819         }
2820
2821         c -= row->pos();
2822         x = int(tmpx);
2823         return c;
2824 }
2825
2826
2827 // returns pointer to a specified row
2828 Row * LyXText::getRow(Paragraph * par, pos_type pos, int & y) const
2829 {
2830         if (!firstrow)
2831                 return 0;
2832
2833         Row * tmprow = firstrow;
2834         y = 0;
2835
2836         // find the first row of the specified paragraph
2837         while (tmprow->next() && tmprow->par() != par) {
2838                 y += tmprow->height();
2839                 tmprow = tmprow->next();
2840         }
2841
2842         // now find the wanted row
2843         while (tmprow->pos() < pos
2844                && tmprow->next()
2845                && tmprow->next()->par() == par
2846                && tmprow->next()->pos() <= pos) {
2847                 y += tmprow->height();
2848                 tmprow = tmprow->next();
2849         }
2850
2851         return tmprow;
2852 }
2853
2854
2855 Row * LyXText::getRowNearY(int & y) const
2856 {
2857 #if 1
2858         // If possible we should optimize this method. (Lgb)
2859         Row * tmprow = firstrow;
2860         int tmpy = 0;
2861
2862         while (tmprow->next() && tmpy + tmprow->height() <= y) {
2863                 tmpy += tmprow->height();
2864                 tmprow = tmprow->next();
2865         }
2866
2867         y = tmpy;   // return the real y
2868
2869         //lyxerr << "returned y = " << y << endl;
2870
2871         return tmprow;
2872 #else
2873         // Search from the current cursor position.
2874
2875         Row * tmprow = cursor.row();
2876         int tmpy = cursor.y() - tmprow->baseline();
2877
2878         lyxerr << "cursor.y() = " << tmpy << endl;
2879         lyxerr << "tmprow->height() = " << tmprow->height() << endl;
2880         lyxerr << "tmprow->baseline() = " << tmprow->baseline() << endl;
2881         lyxerr << "first = " << first << endl;
2882         lyxerr << "y = " << y << endl;
2883
2884         if (y < tmpy) {
2885                 lyxerr << "up" << endl;
2886                 do {
2887                         tmpy -= tmprow->height();
2888                         tmprow = tmprow->previous();
2889                 } while (tmprow && tmpy - tmprow->height() >= y);
2890         } else if (y > tmpy) {
2891                 lyxerr << "down" << endl;
2892
2893                 while (tmprow->next() && tmpy + tmprow->height() <= y) {
2894                         tmpy += tmprow->height();
2895                         tmprow = tmprow->next();
2896                 }
2897         } else {
2898                 lyxerr << "equal" << endl;
2899         }
2900
2901         y = tmpy; // return the real y
2902
2903         lyxerr << "returned y = " << y << endl;
2904
2905         return tmprow;
2906
2907 #endif
2908 }
2909
2910
2911 int LyXText::getDepth() const
2912 {
2913         return cursor.par()->getDepth();
2914 }