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