]> git.lyx.org Git - lyx.git/blob - src/text.C
zlib stuff
[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(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(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(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, getLabelFont(pit));
838                         if (pit->isLineSeparator(i - 1))
839                                 thiswidth -= singleWidth(pit, i - 1);
840                         int left_margin = labelEnd(row);
841                         if (thiswidth + x < left_margin)
842                                 thiswidth = left_margin - x;
843                         thiswidth += singleWidth(pit, i, c);
844                 } else {
845                         // Manual inlined optimised version of common case of "thiswidth = singleWidth(pit, i, c);"
846                         if (IsPrintable(c)) {
847                                 if (pos > endPosOfFontSpan) {
848                                         // We need to get the next font
849                                         font = getFont(pit, i);
850                                         endPosOfFontSpan = pit->getEndPosOfFontSpan(i);
851                                 }
852                                 if (! font.language()->RightToLeft()) {
853                                         thiswidth = font_metrics::width(c, font);
854                                 } else {
855                                         // Fall-back to normal case
856                                         thiswidth = singleWidth(pit, i, c);
857                                         // And flush font cache
858                                         endPosOfFontSpan = 0;
859                                 }
860                         } else {
861                                 // Fall-back to normal case
862                                 thiswidth = singleWidth(pit, i, c);
863                                 // And flush font cache
864                                 endPosOfFontSpan = 0;
865                         }
866                 }
867
868                 x += thiswidth;
869                 chunkwidth += thiswidth;
870
871                 InsetOld * in = pit->isInset(i) ? pit->getInset(i) : 0;
872                 fullrow = (in && (in->display() || in->needFullRow()));
873
874                 // break before a character that will fall off
875                 // the right of the row
876                 if (x >= width) {
877                         // if no break before or we are at an inset
878                         // that will take up a row, break here
879                         if (point == last || fullrow || chunkwidth >= (width - left)) {
880                                 if (pos < i)
881                                         point = i - 1;
882                                 else
883                                         point = i;
884                         }
885                         break;
886                 }
887
888                 if (!in || in->isChar()) {
889                         // some insets are line separators too
890                         if (pit->isLineSeparator(i)) {
891                                 point = i;
892                                 chunkwidth = 0;
893                         }
894                         continue;
895                 }
896
897                 if (!fullrow)
898                         continue;
899
900                 // full row insets start at a new row
901                 if (i == pos) {
902                         if (pos < last - 1) {
903                                 point = i;
904                                 if (pit->isLineSeparator(i + 1))
905                                         ++point;
906                         } else {
907                                 // to avoid extra rows
908                                 point = last;
909                         }
910                 } else {
911                         point = i - 1;
912                 }
913
914                 return point;
915         }
916
917         if (point == last && x >= width) {
918                 // didn't find one, break at the point we reached the edge
919                 point = i;
920         } else if (i == last && x < width) {
921                 // found one, but we fell off the end of the par, so prefer
922                 // that.
923                 point = last;
924         }
925
926         // manual labels cannot be broken in LaTeX. But we
927         // want to make our on-screen rendering of footnotes
928         // etc. still break
929         if (!fullrow && body_pos && point < body_pos)
930                 point = body_pos - 1;
931
932         return point;
933 }
934
935
936 // returns the minimum space a row needs on the screen in pixel
937 int LyXText::fill(RowList::iterator row, int paper_width) const
938 {
939         if (paper_width < 0)
940                 return 0;
941
942         int w;
943         // get the pure distance
944         pos_type const last = lastPrintablePos(*this, row);
945
946         ParagraphList::iterator pit = row->par();
947         LyXLayout_ptr const & layout = pit->layout();
948
949         // special handling of the right address boxes
950         if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX) {
951                 int const tmpfill = row->fill();
952                 row->fill(0); // the minfill in MarginLeft()
953                 w = leftMargin(*row);
954                 row->fill(tmpfill);
955         } else
956                 w = leftMargin(*row);
957
958         pos_type const body_pos = pit->beginningOfBody();
959         pos_type i = row->pos();
960
961         if (! pit->empty() && i <= last) {
962                 // We re-use the font resolution for the entire span when possible
963                 LyXFont font = getFont(pit, i);
964                 lyx::pos_type endPosOfFontSpan = pit->getEndPosOfFontSpan(i);
965                 while (i <= last) {
966                         if (body_pos > 0 && i == body_pos) {
967                                 w += font_metrics::width(layout->labelsep, getLabelFont(pit));
968                                 if (pit->isLineSeparator(i - 1))
969                                         w -= singleWidth(pit, i - 1);
970                                 int left_margin = labelEnd(*row);
971                                 if (w < left_margin)
972                                         w = left_margin;
973                         }
974                         { // Manual inlined an optimised version of the common case of "w += singleWidth(pit, i);"
975                                 char const c = pit->getChar(i);
976
977                                 if (IsPrintable(c)) {
978                                         if (i > endPosOfFontSpan) {
979                                                 // We need to get the next font
980                                                 font = getFont(pit, i);
981                                                 endPosOfFontSpan = pit->getEndPosOfFontSpan(i);
982                                         }
983                                         if (! font.language()->RightToLeft()) {
984                                                 w += font_metrics::width(c, font);
985                                         } else {
986                                                 // Fall-back to the normal case
987                                                 w += singleWidth(pit, i, c);
988                                                 // And flush font cache
989                                                 endPosOfFontSpan = 0;
990                                         }
991                                 } else {
992                                         // Fall-back to the normal case
993                                         w += singleWidth(pit, i, c);
994                                         // And flush font cache
995                                         endPosOfFontSpan = 0;
996                                 }
997                         }
998                         ++i;
999                 }
1000         }
1001         if (body_pos > 0 && body_pos > last) {
1002                 w += font_metrics::width(layout->labelsep, getLabelFont(pit));
1003                 if (last >= 0 && pit->isLineSeparator(last))
1004                         w -= singleWidth(pit, last);
1005                 int const left_margin = labelEnd(*row);
1006                 if (w < left_margin)
1007                         w = left_margin;
1008         }
1009
1010         int const fill = paper_width - w - rightMargin(*bv()->buffer(), *row);
1011
1012         // If this case happens, it means that our calculation
1013         // of the widths of the chars when we do rowBreakPoint()
1014         // went wrong for some reason. Typically in list bodies.
1015         // Things just about hobble on anyway, though you'll end
1016         // up with a "fill_separator" less than zero, which corresponds
1017         // to inter-word spacing being too small. Hopefully this problem
1018         // will die when the label hacks die.
1019         if (lyxerr.debugging() && fill < 0) {
1020                 lyxerr[Debug::GUI] << "Eek, fill() was < 0: " << fill
1021                         << " w " << w << " paper_width " << paper_width
1022                         << " right margin " << rightMargin(*bv()->buffer(), *row) << endl;
1023         }
1024
1025         return fill;
1026 }
1027
1028
1029 // returns the minimum space a manual label needs on the screen in pixel
1030 int LyXText::labelFill(Row const & row) const
1031 {
1032         ParagraphList::iterator pit = row.par();
1033
1034         pos_type last = pit->beginningOfBody();
1035
1036         Assert(last > 0);
1037
1038         // -1 because a label ends either with a space that is in the label,
1039         // or with the beginning of a footnote that is outside the label.
1040         --last;
1041
1042         // a separator at this end does not count
1043         if (pit->isLineSeparator(last))
1044                 --last;
1045
1046         int w = 0;
1047         pos_type i = row.pos();
1048         while (i <= last) {
1049                 w += singleWidth(pit, i);
1050                 ++i;
1051         }
1052
1053         int fill = 0;
1054         string const & labwidstr = pit->params().labelWidthString();
1055         if (!labwidstr.empty()) {
1056                 LyXFont const labfont = getLabelFont(pit);
1057                 int const labwidth = font_metrics::width(labwidstr, labfont);
1058                 fill = max(labwidth - w, 0);
1059         }
1060
1061         return fill;
1062 }
1063
1064
1065 LColor::color LyXText::backgroundColor() const
1066 {
1067         if (inset_owner)
1068                 return inset_owner->backgroundColor();
1069         else
1070                 return LColor::background;
1071 }
1072
1073
1074 void LyXText::setHeightOfRow(RowList::iterator rit)
1075 {
1076         Assert(rit != rows().end());
1077
1078         // get the maximum ascent and the maximum descent
1079         float layoutasc = 0;
1080         float layoutdesc = 0;
1081         float tmptop = 0;
1082
1083         // ok, let us initialize the maxasc and maxdesc value.
1084         // This depends in LaTeX of the font of the last character
1085         // in the paragraph. The hack below is necessary because
1086         // of the possibility of open footnotes
1087
1088         // Correction: only the fontsize count. The other properties
1089         //  are taken from the layoutfont. Nicer on the screen :)
1090         ParagraphList::iterator pit = rit->par();
1091
1092         LyXLayout_ptr const & layout = pit->layout();
1093
1094         // as max get the first character of this row then it can increase but not
1095         // decrease the height. Just some point to start with so we don't have to
1096         // do the assignment below too often.
1097         LyXFont font = getFont(pit, rit->pos());
1098         LyXFont::FONT_SIZE const tmpsize = font.size();
1099         font = getLayoutFont(pit);
1100         LyXFont::FONT_SIZE const size = font.size();
1101         font.setSize(tmpsize);
1102
1103         LyXFont labelfont = getLabelFont(pit);
1104
1105         float spacing_val = 1.0;
1106         if (!pit->params().spacing().isDefault()) {
1107                 spacing_val = pit->params().spacing().getValue();
1108         } else {
1109                 spacing_val = bv()->buffer()->params.spacing.getValue();
1110         }
1111         //lyxerr << "spacing_val = " << spacing_val << endl;
1112
1113         int maxasc = int(font_metrics::maxAscent(font) *
1114                          layout->spacing.getValue() *
1115                          spacing_val);
1116         int maxdesc = int(font_metrics::maxDescent(font) *
1117                           layout->spacing.getValue() *
1118                           spacing_val);
1119
1120         pos_type const pos_end = lastPos(*this, rit);
1121         int labeladdon = 0;
1122         int maxwidth = 0;
1123
1124         if (!pit->empty()) {
1125                 // We re-use the font resolution for the entire font span when possible
1126                 LyXFont font = getFont(pit, rit->pos());
1127                 lyx::pos_type endPosOfFontSpan = pit->getEndPosOfFontSpan(rit->pos());
1128
1129                 // Optimisation
1130                 Paragraph const & par = *pit;
1131
1132                 // Check if any insets are larger
1133                 for (pos_type pos = rit->pos(); pos <= pos_end; ++pos) {
1134                         // Manual inlined optimised version of common case of "maxwidth += singleWidth(pit, pos);"
1135                         char const c = par.getChar(pos);
1136
1137                         if (IsPrintable(c)) {
1138                                 if (pos > endPosOfFontSpan) {
1139                                         // We need to get the next font
1140                                         font = getFont(pit, pos);
1141                                         endPosOfFontSpan = par.getEndPosOfFontSpan(pos);
1142                                 }
1143                                 if (! font.language()->RightToLeft()) {
1144                                         maxwidth += font_metrics::width(c, font);
1145                                 } else {
1146                                         // Fall-back to normal case
1147                                         maxwidth += singleWidth(pit, pos, c);
1148                                         // And flush font cache
1149                                         endPosOfFontSpan = 0;
1150                                 }
1151                         } else {
1152                                 // Special handling of insets - are any larger?
1153                                 if (par.isInset(pos)) {
1154                                         LyXFont const tmpfont = getFont(pit, pos);
1155                                         InsetOld const * tmpinset = par.getInset(pos);
1156                                         if (tmpinset) {
1157 #if 1 // this is needed for deep update on initialitation
1158 #warning inset->update FIXME
1159                                                 //tmpinset->update(bv());
1160                                                 Dimension dim;
1161                                                 MetricsInfo mi(bv(), tmpfont, workWidth());
1162                                                 tmpinset->metrics(mi, dim);
1163                                                 maxwidth += dim.wid;
1164                                                 maxasc = max(maxasc, dim.asc);
1165                                                 maxdesc = max(maxdesc, dim.des);
1166 #else
1167                                                 maxwidth += tmpinset->width();
1168                                                 maxasc = max(maxasc, tmpinset->ascent());
1169                                                 maxdesc = max(maxdesc, tmpinset->descent());
1170 #endif
1171                                         } 
1172                                 } else {
1173                                         // Fall-back to normal case
1174                                         maxwidth += singleWidth(pit, pos, c);
1175                                         // And flush font cache
1176                                         endPosOfFontSpan = 0;
1177                                 }
1178                         }
1179                 }
1180         }
1181
1182         // Check if any custom fonts are larger (Asger)
1183         // This is not completely correct, but we can live with the small,
1184         // cosmetic error for now.
1185         LyXFont::FONT_SIZE maxsize =
1186                 pit->highestFontInRange(rit->pos(), pos_end, size);
1187         if (maxsize > font.size()) {
1188                 font.setSize(maxsize);
1189                 maxasc = max(maxasc, font_metrics::maxAscent(font));
1190                 maxdesc = max(maxdesc, font_metrics::maxDescent(font));
1191         }
1192
1193         // This is nicer with box insets:
1194         ++maxasc;
1195         ++maxdesc;
1196
1197         rit->ascent_of_text(maxasc);
1198
1199         // is it a top line?
1200         if (!rit->pos()) {
1201
1202                 // some parksips VERY EASY IMPLEMENTATION
1203                 if (bv()->buffer()->params.paragraph_separation ==
1204                         BufferParams::PARSEP_SKIP)
1205                 {
1206                         if (layout->isParagraph()
1207                                 && pit->getDepth() == 0
1208                                 && pit != ownerParagraphs().begin())
1209                         {
1210                                 maxasc += bv()->buffer()->params.getDefSkip().inPixels(*bv());
1211                         } else if (pit != ownerParagraphs().begin() &&
1212                                    boost::prior(pit)->layout()->isParagraph() &&
1213                                    boost::prior(pit)->getDepth() == 0)
1214                         {
1215                                 // is it right to use defskip here too? (AS)
1216                                 maxasc += bv()->buffer()->params.getDefSkip().inPixels(*bv());
1217                         }
1218                 }
1219
1220                 // the top margin
1221                 if (pit == ownerParagraphs().begin() && !isInInset())
1222                         maxasc += PAPER_MARGIN;
1223
1224                 // add the vertical spaces, that the user added
1225                 maxasc += getLengthMarkerHeight(*bv(), pit->params().spaceTop());
1226
1227                 // do not forget the DTP-lines!
1228                 // there height depends on the font of the nearest character
1229                 if (pit->params().lineTop())
1230
1231                         maxasc += 2 * font_metrics::ascent('x', getFont(pit, 0));
1232                 // and now the pagebreaks
1233                 if (pit->params().pagebreakTop())
1234                         maxasc += 3 * defaultRowHeight();
1235
1236                 if (pit->params().startOfAppendix())
1237                         maxasc += 3 * defaultRowHeight();
1238
1239                 // This is special code for the chapter, since the label of this
1240                 // layout is printed in an extra row
1241                 if (layout->labeltype == LABEL_COUNTER_CHAPTER
1242                         && bv()->buffer()->params.secnumdepth >= 0)
1243                 {
1244                         float spacing_val = 1.0;
1245                         if (!pit->params().spacing().isDefault()) {
1246                                 spacing_val = pit->params().spacing().getValue();
1247                         } else {
1248                                 spacing_val = bv()->buffer()->params.spacing.getValue();
1249                         }
1250
1251                         labeladdon = int(font_metrics::maxDescent(labelfont) *
1252                                          layout->spacing.getValue() *
1253                                          spacing_val)
1254                                 + int(font_metrics::maxAscent(labelfont) *
1255                                       layout->spacing.getValue() *
1256                                       spacing_val);
1257                 }
1258
1259                 // special code for the top label
1260                 if ((layout->labeltype == LABEL_TOP_ENVIRONMENT
1261                      || layout->labeltype == LABEL_BIBLIO
1262                      || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
1263                     && isFirstInSequence(pit, ownerParagraphs())
1264                     && !pit->getLabelstring().empty())
1265                 {
1266                         float spacing_val = 1.0;
1267                         if (!pit->params().spacing().isDefault()) {
1268                                 spacing_val = pit->params().spacing().getValue();
1269                         } else {
1270                                 spacing_val = bv()->buffer()->params.spacing.getValue();
1271                         }
1272
1273                         labeladdon = int(
1274                                 (font_metrics::maxAscent(labelfont) *
1275                                  layout->spacing.getValue() *
1276                                  spacing_val)
1277                                 +(font_metrics::maxDescent(labelfont) *
1278                                   layout->spacing.getValue() *
1279                                   spacing_val)
1280                                 + layout->topsep * defaultRowHeight()
1281                                 + layout->labelbottomsep * defaultRowHeight());
1282                 }
1283
1284                 // And now the layout spaces, for example before and after
1285                 // a section, or between the items of a itemize or enumerate
1286                 // environment.
1287
1288                 if (!pit->params().pagebreakTop()) {
1289                         ParagraphList::iterator prev =
1290                                 depthHook(pit, ownerParagraphs(),
1291                                           pit->getDepth());
1292                         if (prev != pit && prev->layout() == layout &&
1293                                 prev->getDepth() == pit->getDepth() &&
1294                                 prev->getLabelWidthString() == pit->getLabelWidthString())
1295                         {
1296                                 layoutasc = (layout->itemsep * defaultRowHeight());
1297                         } else if (rit != rows().begin()) {
1298                                 tmptop = layout->topsep;
1299
1300                                 if (boost::prior(pit)->getDepth() >= pit->getDepth())
1301                                         tmptop -= boost::prior(rit)->par()->layout()->bottomsep;
1302
1303                                 if (tmptop > 0)
1304                                         layoutasc = (tmptop * defaultRowHeight());
1305                         } else if (pit->params().lineTop()) {
1306                                 tmptop = layout->topsep;
1307
1308                                 if (tmptop > 0)
1309                                         layoutasc = (tmptop * defaultRowHeight());
1310                         }
1311
1312                         prev = outerHook(pit, ownerParagraphs());
1313                         if (prev != ownerParagraphs().end())  {
1314                                 maxasc += int(prev->layout()->parsep * defaultRowHeight());
1315                         } else if (pit != ownerParagraphs().begin()) {
1316                                 ParagraphList::iterator prior_pit = boost::prior(pit);
1317                                 if (prior_pit->getDepth() != 0 ||
1318                                     prior_pit->layout() == layout) {
1319                                         maxasc += int(layout->parsep * defaultRowHeight());
1320                                 }
1321                         }
1322                 }
1323         }
1324
1325         // is it a bottom line?
1326         RowList::iterator next_rit = boost::next(rit);
1327         if (next_rit == rows().end() || next_rit->par() != pit) {
1328                 // the bottom margin
1329                 ParagraphList::iterator nextpit = boost::next(pit);
1330                 if (nextpit == ownerParagraphs().end() &&
1331                     !isInInset())
1332                         maxdesc += PAPER_MARGIN;
1333
1334                 // add the vertical spaces, that the user added
1335                 maxdesc += getLengthMarkerHeight(*bv(), pit->params().spaceBottom());
1336
1337                 // do not forget the DTP-lines!
1338                 // there height depends on the font of the nearest character
1339                 if (pit->params().lineBottom())
1340                         maxdesc += 2 * font_metrics::ascent('x',
1341                                         getFont(pit, max(pos_type(0), pit->size() - 1)));
1342
1343                 // and now the pagebreaks
1344                 if (pit->params().pagebreakBottom())
1345                         maxdesc += 3 * defaultRowHeight();
1346
1347                 // and now the layout spaces, for example before and after
1348                 // a section, or between the items of a itemize or enumerate
1349                 // environment
1350                 if (!pit->params().pagebreakBottom()
1351                     && nextpit != ownerParagraphs().end()) {
1352                         ParagraphList::iterator comparepit = pit;
1353                         float usual = 0;
1354                         float unusual = 0;
1355
1356                         if (comparepit->getDepth() > nextpit->getDepth()) {
1357                                 usual = (comparepit->layout()->bottomsep * defaultRowHeight());
1358                                 comparepit = depthHook(comparepit, ownerParagraphs(), nextpit->getDepth());
1359                                 if (comparepit->layout()!= nextpit->layout()
1360                                         || nextpit->getLabelWidthString() !=
1361                                         comparepit->getLabelWidthString())
1362                                 {
1363                                         unusual = (comparepit->layout()->bottomsep * defaultRowHeight());
1364                                 }
1365                                 if (unusual > usual)
1366                                         layoutdesc = unusual;
1367                                 else
1368                                         layoutdesc = usual;
1369                         } else if (comparepit->getDepth() ==  nextpit->getDepth()) {
1370
1371                                 if (comparepit->layout() != nextpit->layout()
1372                                         || nextpit->getLabelWidthString() !=
1373                                         comparepit->getLabelWidthString())
1374                                         layoutdesc = int(comparepit->layout()->bottomsep * defaultRowHeight());
1375                         }
1376                 }
1377         }
1378
1379         // incalculate the layout spaces
1380         maxasc += int(layoutasc * 2 / (2 + pit->getDepth()));
1381         maxdesc += int(layoutdesc * 2 / (2 + pit->getDepth()));
1382
1383         // calculate the new height of the text
1384         height -= rit->height();
1385
1386         rit->height(maxasc + maxdesc + labeladdon);
1387         rit->baseline(maxasc + labeladdon);
1388
1389         height += rit->height();
1390
1391         rit->top_of_text(rit->baseline() - font_metrics::maxAscent(font));
1392
1393         int x = 0;
1394         if (layout->margintype != MARGIN_RIGHT_ADDRESS_BOX) {
1395                 int dummy;
1396                 // this IS needed
1397                 rit->width(maxwidth);
1398                 prepareToPrint(rit, x, dummy, dummy, dummy, false);
1399         }
1400         rit->width(int(maxwidth + x));
1401         if (inset_owner) {
1402                 width = max(0, workWidth());
1403                 RowList::iterator it = rows().begin();
1404                 RowList::iterator end = rows().end();
1405                 for (; it != end; ++it) {
1406                         if (it->width() > width)
1407                                 width = it->width();
1408                 }
1409         }
1410 }
1411
1412
1413 // Appends the implicit specified paragraph before the specified row,
1414 // start at the implicit given position
1415 void LyXText::appendParagraph(RowList::iterator rowit)
1416 {
1417         Assert(rowit != rowlist_.end());
1418
1419         pos_type const last = rowit->par()->size();
1420         bool done = false;
1421
1422         do {
1423                 pos_type z = rowBreakPoint(*rowit);
1424
1425                 RowList::iterator tmprow = rowit;
1426
1427                 if (z < last) {
1428                         ++z;
1429                         Row newrow(rowit->par(), z);
1430                         rowit = rowlist_.insert(boost::next(rowit), newrow);
1431                 } else {
1432                         done = true;
1433                 }
1434
1435                 // Set the dimensions of the row
1436                 // fixed fill setting now by calling inset->update() in
1437                 // SingleWidth when needed!
1438                 tmprow->fill(fill(tmprow, workWidth()));
1439                 setHeightOfRow(tmprow);
1440
1441         } while (!done);
1442 }
1443
1444
1445 void LyXText::breakAgain(RowList::iterator rit)
1446 {
1447         Assert(rit != rows().end());
1448
1449         bool not_ready = true;
1450
1451         do  {
1452                 pos_type z = rowBreakPoint(*rit);
1453                 RowList::iterator tmprit = rit;
1454                 RowList::iterator end = rows().end();
1455
1456                 if (z < rit->par()->size()) {
1457                         RowList::iterator next_rit = boost::next(rit);
1458
1459                         if (next_rit == end ||
1460                             (next_rit != end &&
1461                              next_rit->par() != rit->par())) {
1462                                 // insert a new row
1463                                 ++z;
1464                                 Row newrow(rit->par(), z);
1465                                 rit = rowlist_.insert(next_rit, newrow);
1466                         } else  {
1467                                 ++rit;
1468                                 ++z;
1469                                 if (rit->pos() == z)
1470                                         not_ready = false; // the rest will not change
1471                                 else {
1472                                         rit->pos(z);
1473                                 }
1474                         }
1475                 } else {
1476                         // if there are some rows too much, delete them
1477                         // only if you broke the whole paragraph!
1478                         RowList::iterator tmprit2 = rit;
1479                         while (boost::next(tmprit2) != end
1480                                && boost::next(tmprit2)->par() == rit->par()) {
1481                                 ++tmprit2;
1482                         }
1483                         while (tmprit2 != rit) {
1484                                 --tmprit2;
1485                                 removeRow(boost::next(tmprit2));
1486                         }
1487                         not_ready = false;
1488                 }
1489
1490                 // set the dimensions of the row
1491                 tmprit->fill(fill(tmprit, workWidth()));
1492                 setHeightOfRow(tmprit);
1493         } while (not_ready);
1494 }
1495
1496
1497 // this is just a little changed version of break again
1498 void LyXText::breakAgainOneRow(RowList::iterator rit)
1499 {
1500         Assert(rit != rows().end());
1501
1502         pos_type z = rowBreakPoint(*rit);
1503         RowList::iterator tmprit = rit;
1504         RowList::iterator end = rows().end();
1505
1506         if (z < rit->par()->size()) {
1507                 RowList::iterator next_rit = boost::next(rit);
1508
1509                 if (next_rit == end ||
1510                     (next_rit != end &&
1511                      next_rit->par() != rit->par())) {
1512                         // insert a new row
1513                         ++z;
1514                         Row newrow(rit->par(), z);
1515                         rit = rowlist_.insert(next_rit, newrow);
1516                 } else  {
1517                         ++rit;
1518                         ++z;
1519                         if (rit->pos() != z)
1520                                 rit->pos(z);
1521                 }
1522         } else {
1523                 // if there are some rows too much, delete them
1524                 // only if you broke the whole paragraph!
1525                 RowList::iterator tmprit2 = rit;
1526                 while (boost::next(tmprit2) != end
1527                        && boost::next(tmprit2)->par() == rit->par()) {
1528                         ++tmprit2;
1529                 }
1530                 while (tmprit2 != rit) {
1531                         --tmprit2;
1532                         removeRow(boost::next(tmprit2));
1533                 }
1534         }
1535
1536         // set the dimensions of the row
1537         tmprit->fill(fill(tmprit, workWidth()));
1538         setHeightOfRow(tmprit);
1539 }
1540
1541
1542 void LyXText::breakParagraph(ParagraphList & paragraphs, char keep_layout)
1543 {
1544         // allow only if at start or end, or all previous is new text
1545         if (cursor.pos() && cursor.pos() != cursor.par()->size()
1546                 && cursor.par()->isChangeEdited(0, cursor.pos()))
1547                 return;
1548
1549         LyXTextClass const & tclass =
1550                 bv()->buffer()->params.getLyXTextClass();
1551         LyXLayout_ptr const & layout = cursor.par()->layout();
1552
1553         // this is only allowed, if the current paragraph is not empty or caption
1554         // and if it has not the keepempty flag active
1555         if (cursor.par()->empty() && !cursor.par()->allowEmpty()
1556            && layout->labeltype != LABEL_SENSITIVE)
1557                 return;
1558
1559         recordUndo(bv(), Undo::ATOMIC, cursor.par());
1560
1561         // Always break behind a space
1562         //
1563         // It is better to erase the space (Dekel)
1564         if (cursor.pos() < cursor.par()->size()
1565              && cursor.par()->isLineSeparator(cursor.pos()))
1566            cursor.par()->erase(cursor.pos());
1567         // cursor.pos(cursor.pos() + 1);
1568
1569         // break the paragraph
1570         if (keep_layout)
1571                 keep_layout = 2;
1572         else
1573                 keep_layout = layout->isEnvironment();
1574
1575         // we need to set this before we insert the paragraph. IMO the
1576         // breakParagraph call should return a bool if it inserts the
1577         // paragraph before or behind and we should react on that one
1578         // but we can fix this in 1.3.0 (Jug 20020509)
1579         bool const isempty = (cursor.par()->allowEmpty() && cursor.par()->empty());
1580         ::breakParagraph(bv()->buffer()->params, paragraphs, cursor.par(),
1581                          cursor.pos(), keep_layout);
1582
1583         // well this is the caption hack since one caption is really enough
1584         if (layout->labeltype == LABEL_SENSITIVE) {
1585                 if (!cursor.pos())
1586                         // set to standard-layout
1587                         cursor.par()->applyLayout(tclass.defaultLayout());
1588                 else
1589                         // set to standard-layout
1590                         boost::next(cursor.par())->applyLayout(tclass.defaultLayout());
1591         }
1592
1593         // if the cursor is at the beginning of a row without prior newline,
1594         // move one row up!
1595         // This touches only the screen-update. Otherwise we would may have
1596         // an empty row on the screen
1597         if (cursor.pos() && cursorRow()->pos() == cursor.pos()
1598             && !cursorRow()->par()->isNewline(cursor.pos() - 1))
1599         {
1600                 cursorLeft(bv());
1601         }
1602
1603         postPaint();
1604
1605         removeParagraph(cursorRow());
1606
1607         // set the dimensions of the cursor row
1608         cursorRow()->fill(fill(cursorRow(), workWidth()));
1609
1610         setHeightOfRow(cursorRow());
1611
1612 #warning Trouble Point! (Lgb)
1613         // When ::breakParagraph is called from within an inset we must
1614         // ensure that the correct ParagraphList is used. Today that is not
1615         // the case and the Buffer::paragraphs is used. Not good. (Lgb)
1616         ParagraphList::iterator next_par = boost::next(cursor.par());
1617
1618         while (!next_par->empty() && next_par->isNewline(0))
1619                 next_par->erase(0);
1620
1621         insertParagraph(next_par, boost::next(cursorRow()));
1622         updateCounters();
1623
1624         // This check is necessary. Otherwise the new empty paragraph will
1625         // be deleted automatically. And it is more friendly for the user!
1626         if (cursor.pos() || isempty)
1627                 setCursor(next_par, 0);
1628         else
1629                 setCursor(cursor.par(), 0);
1630
1631         if (boost::next(cursorRow()) != rows().end())
1632                 breakAgain(boost::next(cursorRow()));
1633 }
1634
1635
1636 // Just a macro to make some thing easier.
1637 void LyXText::redoParagraph()
1638 {
1639         clearSelection();
1640         redoParagraphs(cursor, boost::next(cursor.par()));
1641         setCursorIntern(cursor.par(), cursor.pos());
1642 }
1643
1644
1645 // insert a character, moves all the following breaks in the
1646 // same Paragraph one to the right and make a rebreak
1647 void LyXText::insertChar(char c)
1648 {
1649         recordUndo(bv(), Undo::INSERT, cursor.par());
1650
1651         // When the free-spacing option is set for the current layout,
1652         // disable the double-space checking
1653
1654         bool const freeSpacing = cursorRow()->par()->layout()->free_spacing ||
1655                 cursorRow()->par()->isFreeSpacing();
1656
1657         if (lyxrc.auto_number) {
1658                 static string const number_operators = "+-/*";
1659                 static string const number_unary_operators = "+-";
1660                 static string const number_seperators = ".,:";
1661
1662                 if (current_font.number() == LyXFont::ON) {
1663                         if (!IsDigit(c) && !contains(number_operators, c) &&
1664                             !(contains(number_seperators, c) &&
1665                               cursor.pos() >= 1 &&
1666                               cursor.pos() < cursor.par()->size() &&
1667                               getFont(cursor.par(), cursor.pos()).number() == LyXFont::ON &&
1668                               getFont(cursor.par(), cursor.pos() - 1).number() == LyXFont::ON)
1669                            )
1670                                 number(bv()); // Set current_font.number to OFF
1671                 } else if (IsDigit(c) &&
1672                            real_current_font.isVisibleRightToLeft()) {
1673                         number(bv()); // Set current_font.number to ON
1674
1675                         if (cursor.pos() > 0) {
1676                                 char const c = cursor.par()->getChar(cursor.pos() - 1);
1677                                 if (contains(number_unary_operators, c) &&
1678                                     (cursor.pos() == 1 ||
1679                                      cursor.par()->isSeparator(cursor.pos() - 2) ||
1680                                      cursor.par()->isNewline(cursor.pos() - 2))
1681                                   ) {
1682                                         setCharFont(
1683                                                     cursor.par(),
1684                                                     cursor.pos() - 1,
1685                                                     current_font);
1686                                 } else if (contains(number_seperators, c) &&
1687                                            cursor.pos() >= 2 &&
1688                                            getFont(
1689                                                    cursor.par(),
1690                                                    cursor.pos() - 2).number() == LyXFont::ON) {
1691                                         setCharFont(
1692                                                     cursor.par(),
1693                                                     cursor.pos() - 1,
1694                                                     current_font);
1695                                 }
1696                         }
1697                 }
1698         }
1699
1700
1701         // First check, if there will be two blanks together or a blank at
1702         // the beginning of a paragraph.
1703         // I decided to handle blanks like normal characters, the main
1704         // difference are the special checks when calculating the row.fill
1705         // (blank does not count at the end of a row) and the check here
1706
1707         // The bug is triggered when we type in a description environment:
1708         // The current_font is not changed when we go from label to main text
1709         // and it should (along with realtmpfont) when we type the space.
1710         // CHECK There is a bug here! (Asger)
1711
1712         LyXFont realtmpfont = real_current_font;
1713         LyXFont rawtmpfont = current_font;
1714         // store the current font.  This is because of the use of cursor
1715         // movements. The moving cursor would refresh the current font
1716
1717         // Get the font that is used to calculate the baselineskip
1718         pos_type const lastpos = cursor.par()->size();
1719         LyXFont rawparfont =
1720                 cursor.par()->getFontSettings(bv()->buffer()->params,
1721                                               lastpos - 1);
1722
1723         bool jumped_over_space = false;
1724
1725         if (!freeSpacing && IsLineSeparatorChar(c)) {
1726                 if ((cursor.pos() > 0
1727                      && cursor.par()->isLineSeparator(cursor.pos() - 1))
1728                     || (cursor.pos() > 0
1729                         && cursor.par()->isNewline(cursor.pos() - 1))
1730                     || (cursor.pos() == 0)) {
1731                         static bool sent_space_message = false;
1732                         if (!sent_space_message) {
1733                                 if (cursor.pos() == 0)
1734                                         bv()->owner()->message(_("You cannot insert a space at the beginning of a paragraph. Please read the Tutorial."));
1735                                 else
1736                                         bv()->owner()->message(_("You cannot type two spaces this way. Please read the Tutorial."));
1737                                 sent_space_message = true;
1738                         }
1739                         charInserted();
1740                         return;
1741                 }
1742         }
1743
1744         // the display inset stuff
1745         if (cursorRow()->pos() < cursorRow()->par()->size()
1746             && cursorRow()->par()->isInset(cursorRow()->pos())) {
1747                 InsetOld * inset = cursorRow()->par()->getInset(cursorRow()->pos());
1748                 if (inset && (inset->display() || inset->needFullRow())) {
1749                         // force a new break
1750                         cursorRow()->fill(-1); // to force a new break
1751                 }
1752         }
1753
1754         // get the cursor row fist
1755         RowList::iterator row = cursorRow();
1756         if (c != Paragraph::META_INSET) {
1757                 // Here case LyXText::InsertInset  already inserted the character
1758                 cursor.par()->insertChar(cursor.pos(), c);
1759         }
1760         setCharFont(cursor.par(), cursor.pos(), rawtmpfont);
1761
1762         if (!jumped_over_space) {
1763                 // refresh the positions
1764                 RowList::iterator tmprow = row;
1765                 while (boost::next(tmprow) != rows().end() &&
1766                        boost::next(tmprow)->par() == row->par()) {
1767                         ++tmprow;
1768                         tmprow->pos(tmprow->pos() + 1);
1769                 }
1770         }
1771
1772         // Is there a break one row above
1773         if (row != rows().begin() &&
1774             boost::prior(row)->par() == row->par()
1775             && (cursor.par()->isLineSeparator(cursor.pos())
1776                 || cursor.par()->isNewline(cursor.pos())
1777                 || ((cursor.pos() + 1 < cursor.par()->size()) &&
1778                     cursor.par()->isInset(cursor.pos() + 1))
1779                 || cursorRow()->fill() == -1))
1780         {
1781                 pos_type z = rowBreakPoint(*boost::prior(row));
1782
1783                 if (z >= row->pos()) {
1784                         row->pos(z + 1);
1785
1786                         // set the dimensions of the row above
1787                         boost::prior(row)->fill(fill(
1788                                                    boost::prior(row),
1789                                                    workWidth()));
1790
1791                         setHeightOfRow(boost::prior(row));
1792
1793                         postPaint();
1794
1795                         breakAgainOneRow(row);
1796
1797                         current_font = rawtmpfont;
1798                         real_current_font = realtmpfont;
1799                         setCursor(cursor.par(), cursor.pos() + 1,
1800                                   false, cursor.boundary());
1801
1802                         // cursor MUST be in row now.
1803                         // check, wether the last characters font has changed.
1804                         if (cursor.pos() && cursor.pos() == cursor.par()->size()
1805                             && rawparfont != rawtmpfont)
1806                                 redoHeightOfParagraph();
1807
1808                         charInserted();
1809                         return;
1810                 }
1811         }
1812
1813         // recalculate the fill of the row
1814         if (row->fill() >= 0) {
1815                 // needed because a newline will set fill to -1. Otherwise
1816                 // we would not get a rebreak!
1817                 row->fill(fill(row, workWidth()));
1818         }
1819
1820         if (c == Paragraph::META_INSET || row->fill() < 0) {
1821                 postPaint();
1822                 breakAgainOneRow(row);
1823
1824                 RowList::iterator next_row = boost::next(row);
1825
1826                 // will the cursor be in another row now?
1827                 if (lastPos(*this, row) <= cursor.pos() + 1 &&
1828                     next_row != rows().end()) {
1829                         if (next_row != rows().end() &&
1830                             next_row->par() == row->par()) {
1831                                 // this should always be true
1832                                 ++row;
1833                         }
1834
1835                         breakAgainOneRow(row);
1836                 }
1837                 current_font = rawtmpfont;
1838                 real_current_font = realtmpfont;
1839
1840                 setCursor(cursor.par(), cursor.pos() + 1, false,
1841                           cursor.boundary());
1842                 if (isBoundary(bv()->buffer(), *cursor.par(), cursor.pos())
1843                     != cursor.boundary())
1844                         setCursor(cursor.par(), cursor.pos(), false,
1845                           !cursor.boundary());
1846         } else {
1847                 // FIXME: similar code is duplicated all over - make resetHeightOfRow
1848                 setHeightOfRow(row);
1849                 postPaint();
1850
1851                 current_font = rawtmpfont;
1852                 real_current_font = realtmpfont;
1853                 setCursor(cursor.par(), cursor.pos() + 1, false,
1854                           cursor.boundary());
1855         }
1856
1857         // check, wether the last characters font has changed.
1858         if (cursor.pos() && cursor.pos() == cursor.par()->size()
1859             && rawparfont != rawtmpfont) {
1860                 redoHeightOfParagraph();
1861         }
1862
1863         charInserted();
1864 }
1865
1866
1867 void LyXText::charInserted()
1868 {
1869         // Here we could call FinishUndo for every 20 characters inserted.
1870         // This is from my experience how emacs does it. (Lgb)
1871         static unsigned int counter;
1872         if (counter < 20) {
1873                 ++counter;
1874         } else {
1875                 finishUndo();
1876                 counter = 0;
1877         }
1878 }
1879
1880
1881 void LyXText::prepareToPrint(RowList::iterator rit, int & x,
1882                              int & fill_separator,
1883                              int & fill_hfill,
1884                              int & fill_label_hfill,
1885                              bool bidi) const
1886 {
1887         int w = rit->fill();
1888         fill_hfill = 0;
1889         fill_label_hfill = 0;
1890         fill_separator = 0;
1891         fill_label_hfill = 0;
1892
1893         ParagraphList::iterator pit = rit->par();
1894
1895         bool const is_rtl =
1896                 pit->isRightToLeftPar(bv()->buffer()->params);
1897         if (is_rtl)
1898                 x = workWidth() > 0 ? rightMargin(*bv()->buffer(), *rit) : 0;
1899         else
1900                 x = workWidth() > 0 ? leftMargin(*rit) : 0;
1901
1902         // is there a manual margin with a manual label
1903         LyXLayout_ptr const & layout = pit->layout();
1904
1905         if (layout->margintype == MARGIN_MANUAL
1906             && layout->labeltype == LABEL_MANUAL) {
1907                 /// We might have real hfills in the label part
1908                 int nlh = numberOfLabelHfills(*this, rit);
1909
1910                 // A manual label par (e.g. List) has an auto-hfill
1911                 // between the label text and the body of the
1912                 // paragraph too.
1913                 // But we don't want to do this auto hfill if the par
1914                 // is empty.
1915                 if (!pit->empty())
1916                         ++nlh;
1917
1918                 if (nlh && !pit->getLabelWidthString().empty()) {
1919                         fill_label_hfill = int(labelFill(*rit) / nlh);
1920                 }
1921         }
1922
1923         // are there any hfills in the row?
1924         int const nh = numberOfHfills(*this, rit);
1925
1926         if (nh) {
1927                 if (w > 0)
1928                         fill_hfill = w / nh;
1929         // we don't have to look at the alignment if it is ALIGN_LEFT and
1930         // if the row is already larger then the permitted width as then
1931         // we force the LEFT_ALIGN'edness!
1932         } else if (int(rit->width()) < workWidth()) {
1933                 // is it block, flushleft or flushright?
1934                 // set x how you need it
1935                 int align;
1936                 if (pit->params().align() == LYX_ALIGN_LAYOUT) {
1937                         align = layout->align;
1938                 } else {
1939                         align = pit->params().align();
1940                 }
1941
1942                 // center displayed insets
1943                 InsetOld * inset = 0;
1944                 if (rit->pos() < pit->size()
1945                     && pit->isInset(rit->pos())
1946                     && (inset = pit->getInset(rit->pos()))
1947                     && (inset->display())) // || (inset->scroll() < 0)))
1948                     align = (inset->lyxCode() == InsetOld::MATHMACRO_CODE)
1949                         ? LYX_ALIGN_BLOCK : LYX_ALIGN_CENTER;
1950                 // ERT insets should always be LEFT ALIGNED on screen
1951                 inset = pit->inInset();
1952                 if (inset && inset->owner() &&
1953                         inset->owner()->lyxCode() == InsetOld::ERT_CODE)
1954                 {
1955                         align = LYX_ALIGN_LEFT;
1956                 }
1957
1958                 switch (align) {
1959             case LYX_ALIGN_BLOCK:
1960             {
1961                         int const ns = numberOfSeparators(*this, rit);
1962                         RowList::iterator next_row = boost::next(rit);
1963                         ParagraphList::iterator next_pit = next_row->par();
1964
1965                         if (ns && next_row != rowlist_.end() &&
1966                             next_pit == pit &&
1967                             !(next_pit->isNewline(next_row->pos() - 1))
1968                             && !(next_pit->isInset(next_row->pos()) &&
1969                                  next_pit->getInset(next_row->pos()) &&
1970                                  next_pit->getInset(next_row->pos())->display())
1971                                 ) {
1972                                 fill_separator = w / ns;
1973                         } else if (is_rtl) {
1974                                 x += w;
1975                         }
1976                         break;
1977             }
1978             case LYX_ALIGN_RIGHT:
1979                         x += w;
1980                         break;
1981             case LYX_ALIGN_CENTER:
1982                         x += w / 2;
1983                         break;
1984                 }
1985         }
1986         if (!bidi)
1987                 return;
1988
1989         computeBidiTables(bv()->buffer(), rit);
1990         if (is_rtl) {
1991                 pos_type body_pos = pit->beginningOfBody();
1992                 pos_type last = lastPos(*this, rit);
1993
1994                 if (body_pos > 0 &&
1995                     (body_pos - 1 > last ||
1996                      !pit->isLineSeparator(body_pos - 1))) {
1997                         x += font_metrics::width(layout->labelsep, getLabelFont(pit));
1998                         if (body_pos - 1 <= last)
1999                                 x += fill_label_hfill;
2000                 }
2001         }
2002 }
2003
2004
2005 // important for the screen
2006
2007
2008 // the cursor set functions have a special mechanism. When they
2009 // realize, that you left an empty paragraph, they will delete it.
2010 // They also delete the corresponding row
2011
2012 void LyXText::cursorRightOneWord()
2013 {
2014         ::cursorRightOneWord(cursor, ownerParagraphs());
2015         setCursor(cursor.par(), cursor.pos());
2016 }
2017
2018
2019 // Skip initial whitespace at end of word and move cursor to *start*
2020 // of prior word, not to end of next prior word.
2021 void LyXText::cursorLeftOneWord()
2022 {
2023         LyXCursor tmpcursor = cursor;
2024         ::cursorLeftOneWord(tmpcursor, ownerParagraphs());
2025         setCursor(tmpcursor.par(), tmpcursor.pos());
2026 }
2027
2028
2029 void LyXText::selectWord(word_location loc)
2030 {
2031         LyXCursor from = cursor;
2032         LyXCursor to;
2033         ::getWord(from, to, loc, ownerParagraphs());
2034         if (cursor != from)
2035                 setCursor(from.par(), from.pos());
2036         if (to == from)
2037                 return;
2038         selection.cursor = cursor;
2039         setCursor(to.par(), to.pos());
2040         setSelection();
2041 }
2042
2043
2044 // Select the word currently under the cursor when no
2045 // selection is currently set
2046 bool LyXText::selectWordWhenUnderCursor(word_location loc)
2047 {
2048         if (!selection.set()) {
2049                 selectWord(loc);
2050                 return selection.set();
2051         }
2052         return false;
2053 }
2054
2055
2056 void LyXText::acceptChange()
2057 {
2058         if (!selection.set() && cursor.par()->size())
2059                 return;
2060
2061         if (selection.start.par() == selection.end.par()) {
2062                 LyXCursor & startc = selection.start;
2063                 LyXCursor & endc = selection.end;
2064                 recordUndo(bv(), Undo::INSERT, startc.par());
2065                 startc.par()->acceptChange(startc.pos(), endc.pos());
2066                 finishUndo();
2067                 clearSelection();
2068                 redoParagraphs(startc, boost::next(startc.par()));
2069                 setCursorIntern(startc.par(), 0);
2070         }
2071 #warning handle multi par selection
2072 }
2073
2074
2075 void LyXText::rejectChange()
2076 {
2077         if (!selection.set() && cursor.par()->size())
2078                 return;
2079
2080         if (selection.start.par() == selection.end.par()) {
2081                 LyXCursor & startc = selection.start;
2082                 LyXCursor & endc = selection.end;
2083                 recordUndo(bv(), Undo::INSERT, startc.par());
2084                 startc.par()->rejectChange(startc.pos(), endc.pos());
2085                 finishUndo();
2086                 clearSelection();
2087                 redoParagraphs(startc, boost::next(startc.par()));
2088                 setCursorIntern(startc.par(), 0);
2089         }
2090 #warning handle multi par selection
2091 }
2092
2093
2094 // This function is only used by the spellchecker for NextWord().
2095 // It doesn't handle LYX_ACCENTs and probably never will.
2096 WordLangTuple const
2097 LyXText::selectNextWordToSpellcheck(float & value)
2098 {
2099         if (the_locking_inset) {
2100                 WordLangTuple word = the_locking_inset->selectNextWordToSpellcheck(bv(), value);
2101                 if (!word.word().empty()) {
2102                         value += float(cursor.y());
2103                         value /= float(height);
2104                         return word;
2105                 }
2106                 // we have to go on checking so move cursor to the next char
2107                 if (cursor.pos() == cursor.par()->size()) {
2108                         if (boost::next(cursor.par()) == ownerParagraphs().end())
2109                                 return word;
2110                         cursor.par(boost::next(cursor.par()));
2111                         cursor.pos(0);
2112                 } else
2113                         cursor.pos(cursor.pos() + 1);
2114         }
2115         ParagraphList::iterator tmppit = cursor.par();
2116
2117         // If this is not the very first word, skip rest of
2118         // current word because we are probably in the middle
2119         // of a word if there is text here.
2120         if (cursor.pos() || cursor.par() != ownerParagraphs().begin()) {
2121                 while (cursor.pos() < cursor.par()->size()
2122                        && cursor.par()->isLetter(cursor.pos()))
2123                         cursor.pos(cursor.pos() + 1);
2124         }
2125
2126         // Now, skip until we have real text (will jump paragraphs)
2127         while (true) {
2128                 ParagraphList::iterator cpit = cursor.par();
2129                 pos_type const cpos(cursor.pos());
2130
2131                 if (cpos == cpit->size()) {
2132                         if (boost::next(cpit) != ownerParagraphs().end()) {
2133                                 cursor.par(boost::next(cpit));
2134                                 cursor.pos(0);
2135                                 continue;
2136                         }
2137                         break;
2138                 }
2139
2140                 bool const is_good_inset = cpit->isInset(cpos)
2141                         && cpit->getInset(cpos)->allowSpellcheck();
2142
2143                 if (!isDeletedText(*cpit, cpos)
2144                     && (is_good_inset || cpit->isLetter(cpos)))
2145                         break;
2146
2147                 cursor.pos(cpos + 1);
2148         }
2149
2150         // now check if we hit an inset so it has to be a inset containing text!
2151         if (cursor.pos() < cursor.par()->size() &&
2152             cursor.par()->isInset(cursor.pos())) {
2153                 // lock the inset!
2154                 FuncRequest cmd(bv(), LFUN_INSET_EDIT, "left");
2155                 cursor.par()->getInset(cursor.pos())->localDispatch(cmd);
2156                 // now call us again to do the above trick
2157                 // but obviously we have to start from down below ;)
2158                 return bv()->text->selectNextWordToSpellcheck(value);
2159         }
2160
2161         // Update the value if we changed paragraphs
2162         if (cursor.par() != tmppit) {
2163                 setCursor(cursor.par(), cursor.pos());
2164                 value = float(cursor.y())/float(height);
2165         }
2166
2167         // Start the selection from here
2168         selection.cursor = cursor;
2169
2170         string lang_code = getFont(cursor.par(), cursor.pos()).language()->code();
2171         // and find the end of the word (insets like optional hyphens
2172         // and ligature break are part of a word)
2173         while (cursor.pos() < cursor.par()->size()
2174                && cursor.par()->isLetter(cursor.pos())
2175                && !isDeletedText(*cursor.par(), cursor.pos()))
2176                 cursor.pos(cursor.pos() + 1);
2177
2178         // Finally, we copy the word to a string and return it
2179         string str;
2180         if (selection.cursor.pos() < cursor.pos()) {
2181                 pos_type i;
2182                 for (i = selection.cursor.pos(); i < cursor.pos(); ++i) {
2183                         if (!cursor.par()->isInset(i))
2184                                 str += cursor.par()->getChar(i);
2185                 }
2186         }
2187         return WordLangTuple(str, lang_code);
2188 }
2189
2190
2191 // This one is also only for the spellchecker
2192 void LyXText::selectSelectedWord()
2193 {
2194         if (the_locking_inset) {
2195                 the_locking_inset->selectSelectedWord(bv());
2196                 return;
2197         }
2198         // move cursor to the beginning
2199         setCursor(selection.cursor.par(), selection.cursor.pos());
2200
2201         // set the sel cursor
2202         selection.cursor = cursor;
2203
2204         // now find the end of the word
2205         while (cursor.pos() < cursor.par()->size()
2206                && (cursor.par()->isLetter(cursor.pos())))
2207                 cursor.pos(cursor.pos() + 1);
2208
2209         setCursor(cursor.par(), cursor.pos());
2210
2211         // finally set the selection
2212         setSelection();
2213 }
2214
2215
2216 // Delete from cursor up to the end of the current or next word.
2217 void LyXText::deleteWordForward()
2218 {
2219         if (cursor.par()->empty())
2220                 cursorRight(bv());
2221         else {
2222                 LyXCursor tmpcursor = cursor;
2223                 selection.set(true); // to avoid deletion
2224                 cursorRightOneWord();
2225                 setCursor(tmpcursor, tmpcursor.par(), tmpcursor.pos());
2226                 selection.cursor = cursor;
2227                 cursor = tmpcursor;
2228                 setSelection();
2229
2230                 // Great, CutSelection() gets rid of multiple spaces.
2231                 cutSelection(true, false);
2232         }
2233 }
2234
2235
2236 // Delete from cursor to start of current or prior word.
2237 void LyXText::deleteWordBackward()
2238 {
2239         if (cursor.par()->empty())
2240                 cursorLeft(bv());
2241         else {
2242                 LyXCursor tmpcursor = cursor;
2243                 selection.set(true); // to avoid deletion
2244                 cursorLeftOneWord();
2245                 setCursor(tmpcursor, tmpcursor.par(), tmpcursor.pos());
2246                 selection.cursor = cursor;
2247                 cursor = tmpcursor;
2248                 setSelection();
2249                 cutSelection(true, false);
2250         }
2251 }
2252
2253
2254 // Kill to end of line.
2255 void LyXText::deleteLineForward()
2256 {
2257         if (cursor.par()->empty())
2258                 // Paragraph is empty, so we just go to the right
2259                 cursorRight(bv());
2260         else {
2261                 LyXCursor tmpcursor = cursor;
2262                 // We can't store the row over a regular setCursor
2263                 // so we set it to 0 and reset it afterwards.
2264                 selection.set(true); // to avoid deletion
2265                 cursorEnd();
2266                 setCursor(tmpcursor, tmpcursor.par(), tmpcursor.pos());
2267                 selection.cursor = cursor;
2268                 cursor = tmpcursor;
2269                 setSelection();
2270                 // What is this test for ??? (JMarc)
2271                 if (!selection.set()) {
2272                         deleteWordForward();
2273                 } else {
2274                         cutSelection(true, false);
2275                 }
2276         }
2277 }
2278
2279
2280 void LyXText::changeCase(LyXText::TextCase action)
2281 {
2282         LyXCursor from;
2283         LyXCursor to;
2284
2285         if (selection.set()) {
2286                 from = selection.start;
2287                 to = selection.end;
2288         } else {
2289                 from = cursor;
2290                 ::getWord(from, to, lyx::PARTIAL_WORD, ownerParagraphs());
2291                 setCursor(to.par(), to.pos() + 1);
2292         }
2293
2294         recordUndo(bv(), Undo::ATOMIC, from.par(), to.par());
2295
2296         pos_type pos = from.pos();
2297         ParagraphList::iterator pit = from.par();
2298
2299         while (pit != ownerParagraphs().end() &&
2300                (pos != to.pos() || pit != to.par())) {
2301                 if (pos == pit->size()) {
2302                         ++pit;
2303                         pos = 0;
2304                         continue;
2305                 }
2306                 unsigned char c = pit->getChar(pos);
2307                 if (!IsInsetChar(c)) {
2308                         switch (action) {
2309                         case text_lowercase:
2310                                 c = lowercase(c);
2311                                 break;
2312                         case text_capitalization:
2313                                 c = uppercase(c);
2314                                 action = text_lowercase;
2315                                 break;
2316                         case text_uppercase:
2317                                 c = uppercase(c);
2318                                 break;
2319                         }
2320                 }
2321 #warning changes
2322                 pit->setChar(pos, c);
2323                 checkParagraph(pit, pos);
2324
2325                 ++pos;
2326         }
2327
2328         if (getRow(to) != getRow(from))
2329                 postPaint();
2330 }
2331
2332
2333 void LyXText::Delete()
2334 {
2335         // this is a very easy implementation
2336
2337         LyXCursor old_cursor = cursor;
2338         int const old_cur_par_id = old_cursor.par()->id();
2339         int const old_cur_par_prev_id =
2340                 (old_cursor.par() != ownerParagraphs().begin() ?
2341                  boost::prior(old_cursor.par())->id() : -1);
2342
2343         // just move to the right
2344         cursorRight(bv());
2345
2346         // CHECK Look at the comment here.
2347         // This check is not very good...
2348         // The cursorRightIntern calls DeleteEmptyParagrapgMechanism
2349         // and that can very well delete the par or par->previous in
2350         // old_cursor. Will a solution where we compare paragraph id's
2351         //work better?
2352         if ((cursor.par() != ownerParagraphs().begin() ? boost::prior(cursor.par())->id() : -1)
2353             == old_cur_par_prev_id
2354             && cursor.par()->id() != old_cur_par_id) {
2355                 // delete-empty-paragraph-mechanism has done it
2356                 return;
2357         }
2358
2359         // if you had success make a backspace
2360         if (old_cursor.par() != cursor.par() || old_cursor.pos() != cursor.pos()) {
2361                 LyXCursor tmpcursor = cursor;
2362                 // to make sure undo gets the right cursor position
2363                 cursor = old_cursor;
2364                 recordUndo(bv(), Undo::DELETE, cursor.par());
2365                 cursor = tmpcursor;
2366                 backspace();
2367         }
2368 }
2369
2370
2371 void LyXText::backspace()
2372 {
2373         // Get the font that is used to calculate the baselineskip
2374         pos_type lastpos = cursor.par()->size();
2375         LyXFont rawparfont =
2376                 cursor.par()->getFontSettings(bv()->buffer()->params,
2377                                               lastpos - 1);
2378
2379         if (cursor.pos() == 0) {
2380                 // The cursor is at the beginning of a paragraph,
2381                 // so the the backspace will collapse two paragraphs into one.
2382
2383                 // but it's not allowed unless it's new
2384                 if (cursor.par()->isChangeEdited(0, cursor.par()->size()))
2385                         return;
2386
2387                 // we may paste some paragraphs
2388
2389                 // is it an empty paragraph?
2390
2391                 if ((lastpos == 0
2392                      || (lastpos == 1 && cursor.par()->isSeparator(0)))) {
2393                         // This is an empty paragraph and we delete it just by moving the cursor one step
2394                         // left and let the DeleteEmptyParagraphMechanism handle the actual deletion
2395                         // of the paragraph.
2396
2397                         if (cursor.par() != ownerParagraphs().begin()) {
2398                                 ParagraphList::iterator tmppit = boost::prior(cursor.par());
2399                                 if (cursor.par()->layout() == tmppit->layout()
2400                                     && cursor.par()->getAlign() == tmppit->getAlign()) {
2401                                         // Inherit bottom DTD from the paragraph below.
2402                                         // (the one we are deleting)
2403                                         tmppit->params().lineBottom(cursor.par()->params().lineBottom());
2404                                         tmppit->params().spaceBottom(cursor.par()->params().spaceBottom());
2405                                         tmppit->params().pagebreakBottom(cursor.par()->params().pagebreakBottom());
2406                                 }
2407
2408                                 cursorLeft(bv());
2409
2410                                 // the layout things can change the height of a row !
2411                                 int const tmpheight = cursorRow()->height();
2412                                 setHeightOfRow(cursorRow());
2413                                 if (cursorRow()->height() != tmpheight)
2414                                         postPaint();
2415                                 return;
2416                         }
2417                 }
2418
2419                 if (cursor.par() != ownerParagraphs().begin()) {
2420                         recordUndo(bv(), Undo::DELETE,
2421                                 boost::prior(cursor.par()),
2422                                 cursor.par());
2423                 }
2424
2425                 ParagraphList::iterator tmppit = cursor.par();
2426                 RowList::iterator tmprow = cursorRow();
2427
2428                 // We used to do cursorLeftIntern() here, but it is
2429                 // not a good idea since it triggers the auto-delete
2430                 // mechanism. So we do a cursorLeftIntern()-lite,
2431                 // without the dreaded mechanism. (JMarc)
2432                 if (cursor.par() != ownerParagraphs().begin()) {
2433                         // steps into the above paragraph.
2434                         setCursorIntern(boost::prior(cursor.par()),
2435                                         boost::prior(cursor.par())->size(),
2436                                         false);
2437                 }
2438
2439                 // Pasting is not allowed, if the paragraphs have different
2440                 // layout. I think it is a real bug of all other
2441                 // word processors to allow it. It confuses the user.
2442                 // Even so with a footnote paragraph and a non-footnote
2443                 // paragraph. I will not allow pasting in this case,
2444                 // because the user would be confused if the footnote behaves
2445                 // different wether it is open or closed.
2446
2447                 //      Correction: Pasting is always allowed with standard-layout
2448                 LyXTextClass const & tclass =
2449                         bv()->buffer()->params.getLyXTextClass();
2450
2451                 if (cursor.par() != tmppit
2452                     && (cursor.par()->layout() == tmppit->layout()
2453                         || tmppit->layout() == tclass.defaultLayout())
2454                     && cursor.par()->getAlign() == tmppit->getAlign()) {
2455                         removeParagraph(tmprow);
2456                         removeRow(tmprow);
2457                         mergeParagraph(bv()->buffer()->params, bv()->buffer()->paragraphs, cursor.par());
2458
2459                         if (!cursor.pos() || !cursor.par()->isSeparator(cursor.pos() - 1))
2460                                 ; //cursor.par()->insertChar(cursor.pos(), ' ');
2461                         // strangely enough it seems that commenting out the line above removes
2462                         // most or all of the segfaults. I will however also try to move the
2463                         // two Remove... lines in front of the PasteParagraph too.
2464                         else
2465                                 if (cursor.pos())
2466                                         cursor.pos(cursor.pos() - 1);
2467
2468                         postPaint();
2469
2470                         // remove the lost paragraph
2471                         // This one is not safe, since the paragraph that the tmprow and the
2472                         // following rows belong to has been deleted by the PasteParagraph
2473                         // above. The question is... could this be moved in front of the
2474                         // PasteParagraph?
2475                         //RemoveParagraph(tmprow);
2476                         //RemoveRow(tmprow);
2477
2478                         // This rebuilds the rows.
2479                         appendParagraph(cursorRow());
2480                         updateCounters();
2481
2482                         // the row may have changed, block, hfills etc.
2483                         setCursor(cursor.par(), cursor.pos(), false);
2484                 }
2485         } else {
2486                 // this is the code for a normal backspace, not pasting
2487                 // any paragraphs
2488                 recordUndo(bv(), Undo::DELETE, cursor.par());
2489                 // We used to do cursorLeftIntern() here, but it is
2490                 // not a good idea since it triggers the auto-delete
2491                 // mechanism. So we do a cursorLeftIntern()-lite,
2492                 // without the dreaded mechanism. (JMarc)
2493                 setCursorIntern(cursor.par(), cursor.pos()- 1,
2494                                 false, cursor.boundary());
2495
2496                 if (cursor.par()->isInset(cursor.pos())) {
2497                         // force complete redo when erasing display insets
2498                         // this is a cruel method but safe..... Matthias
2499                         if (cursor.par()->getInset(cursor.pos())->display() ||
2500                             cursor.par()->getInset(cursor.pos())->needFullRow()) {
2501                                 cursor.par()->erase(cursor.pos());
2502                                 redoParagraph();
2503                                 return;
2504                         }
2505                 }
2506
2507                 RowList::iterator row = cursorRow();
2508                 int y = cursor.y() - row->baseline();
2509                 pos_type z;
2510                 // remember that a space at the end of a row doesnt count
2511                 // when calculating the fill
2512                 if (cursor.pos() < lastPos(*this, row) ||
2513                     !cursor.par()->isLineSeparator(cursor.pos())) {
2514                         row->fill(row->fill() + singleWidth(
2515                                                             cursor.par(),
2516                                                             cursor.pos()));
2517                 }
2518
2519                 // some special code when deleting a newline. This is similar
2520                 // to the behavior when pasting paragraphs
2521                 if (cursor.pos() && cursor.par()->isNewline(cursor.pos())) {
2522                         cursor.par()->erase(cursor.pos());
2523                         // refresh the positions
2524                         RowList::iterator tmprow = row;
2525                         while (boost::next(tmprow) != rows().end() &&
2526                                boost::next(tmprow)->par() == row->par()) {
2527                                 ++tmprow;
2528                                 tmprow->pos(tmprow->pos() - 1);
2529                         }
2530                         if (cursor.par()->isLineSeparator(cursor.pos() - 1))
2531                                 cursor.pos(cursor.pos() - 1);
2532
2533                         if (cursor.pos() < cursor.par()->size()
2534                             && !cursor.par()->isSeparator(cursor.pos())) {
2535                                 cursor.par()->insertChar(cursor.pos(), ' ');
2536                                 setCharFont(cursor.par(), cursor.pos(), current_font);
2537                                 // refresh the positions
2538                                 tmprow = row;
2539                                 while (boost::next(tmprow) != rows().end() &&
2540                                        boost::next(tmprow)->par() == row->par()) {
2541                                         ++tmprow;
2542                                         tmprow->pos(tmprow->pos() + 1);
2543                                 }
2544                         }
2545                 } else {
2546                         cursor.par()->erase(cursor.pos());
2547
2548                         // refresh the positions
2549                         RowList::iterator tmprow = row;
2550                         while (boost::next(tmprow) != rows().end() &&
2551                                boost::next(tmprow)->par() == row->par()) {
2552                                 ++tmprow;
2553                                 tmprow->pos(tmprow->pos() - 1);
2554                         }
2555
2556                         // delete newlines at the beginning of paragraphs
2557                         while (!cursor.par()->empty() &&
2558                                cursor.pos() < cursor.par()->size() &&
2559                                cursor.par()->isNewline(cursor.pos()) &&
2560                                cursor.pos() == cursor.par()->beginningOfBody()) {
2561                                 cursor.par()->erase(cursor.pos());
2562                                 // refresh the positions
2563                                 tmprow = row;
2564                                 while (boost::next(tmprow) != rows().end() &&
2565                                        boost::next(tmprow)->par() == row->par()) {
2566                                         ++tmprow;
2567                                         tmprow->pos(tmprow->pos() - 1);
2568                                 }
2569                         }
2570                 }
2571
2572                 // is there a break one row above
2573                 if (row != rows().begin() && boost::prior(row)->par() == row->par()) {
2574                         z = rowBreakPoint(*boost::prior(row));
2575                         if (z >= row->pos()) {
2576                                 row->pos(z + 1);
2577
2578                                 RowList::iterator tmprow = boost::prior(row);
2579
2580                                 // maybe the current row is now empty
2581                                 if (row->pos() >= row->par()->size()) {
2582                                         // remove it
2583                                         removeRow(row);
2584                                 } else {
2585                                         breakAgainOneRow(row);
2586                                 }
2587
2588                                 // set the dimensions of the row above
2589                                 y -= tmprow->height();
2590                                 tmprow->fill(fill(tmprow, workWidth()));
2591                                 setHeightOfRow(tmprow);
2592                                 postPaint();
2593
2594                                 setCursor(cursor.par(), cursor.pos(),
2595                                           false, cursor.boundary());
2596                                 //current_font = rawtmpfont;
2597                                 //real_current_font = realtmpfont;
2598                                 // check, whether the last character's font has changed.
2599                                 if (rawparfont !=
2600                                     cursor.par()->getFontSettings(bv()->buffer()->params,
2601                                                                   cursor.par()->size() - 1))
2602                                         redoHeightOfParagraph();
2603                                 return;
2604                         }
2605                 }
2606
2607                 // break the cursor row again
2608                 if (boost::next(row) != rows().end() &&
2609                     boost::next(row)->par() == row->par() &&
2610                     (lastPos(*this, row) == row->par()->size() - 1 ||
2611                      rowBreakPoint(*row) != lastPos(*this, row))) {
2612
2613                         // it can happen that a paragraph loses one row
2614                         // without a real breakup. This is when a word
2615                         // is to long to be broken. Well, I don t care this
2616                         // hack ;-)
2617                         if (lastPos(*this, row) == row->par()->size() - 1)
2618                                 removeRow(boost::next(row));
2619
2620                         postPaint();
2621
2622                         breakAgainOneRow(row);
2623                         // will the cursor be in another row now?
2624                         if (boost::next(row) != rows().end() &&
2625                             boost::next(row)->par() == row->par() &&
2626                             lastPos(*this, row) <= cursor.pos()) {
2627                                 ++row;
2628                                 breakAgainOneRow(row);
2629                         }
2630
2631                         setCursor(cursor.par(), cursor.pos(), false, cursor.boundary());
2632                 } else  {
2633                         // set the dimensions of the row
2634                         row->fill(fill(row, workWidth()));
2635                         setHeightOfRow(row);
2636                         postPaint();
2637                         setCursor(cursor.par(), cursor.pos(), false, cursor.boundary());
2638                 }
2639         }
2640
2641         // current_font = rawtmpfont;
2642         // real_current_font = realtmpfont;
2643
2644         if (isBoundary(bv()->buffer(), *cursor.par(), cursor.pos())
2645             != cursor.boundary())
2646                 setCursor(cursor.par(), cursor.pos(), false,
2647                           !cursor.boundary());
2648
2649         lastpos = cursor.par()->size();
2650         if (cursor.pos() == lastpos)
2651                 setCurrentFont();
2652
2653         // check, whether the last characters font has changed.
2654         if (rawparfont !=
2655             cursor.par()->getFontSettings(bv()->buffer()->params, lastpos - 1)) {
2656                 redoHeightOfParagraph();
2657         }
2658 }
2659
2660
2661 RowList::iterator LyXText::cursorRow() const
2662 {
2663         return getRow(cursor.par(), cursor.pos());
2664 }
2665
2666
2667 RowList::iterator LyXText::getRow(LyXCursor const & cur) const
2668 {
2669         return getRow(cur.par(), cur.pos());
2670 }
2671
2672
2673 RowList::iterator
2674 LyXText::getRow(ParagraphList::iterator pit, pos_type pos) const
2675 {
2676         if (rows().empty())
2677                 return rowlist_.end();
2678
2679         // find the first row of the specified paragraph
2680         RowList::iterator rit = rowlist_.begin();
2681         RowList::iterator end = rowlist_.end();
2682         while (boost::next(rit) != end && rit->par() != pit) {
2683                 ++rit;
2684         }
2685
2686         // now find the wanted row
2687         while (rit->pos() < pos
2688                && boost::next(rit) != end
2689                && boost::next(rit)->par() == pit
2690                && boost::next(rit)->pos() <= pos) {
2691                 ++rit;
2692         }
2693
2694         return rit;
2695 }
2696
2697
2698 // returns pointer to a specified row
2699 RowList::iterator
2700 LyXText::getRow(ParagraphList::iterator pit, pos_type pos, int & y) const
2701 {
2702         y = 0;
2703
2704         if (rows().empty())
2705                 return rowlist_.end();
2706
2707         // find the first row of the specified paragraph
2708         RowList::iterator rit = rowlist_.begin();
2709         RowList::iterator end = rowlist_.end();
2710         while (boost::next(rit) != end && rit->par() != pit) {
2711                 y += rit->height();
2712                 ++rit;
2713         }
2714
2715         // now find the wanted row
2716         while (rit->pos() < pos
2717                && boost::next(rit) != end
2718                && boost::next(rit)->par() == pit
2719                && boost::next(rit)->pos() <= pos) {
2720                 y += rit->height();
2721                 ++rit;
2722         }
2723
2724         return rit;
2725 }
2726
2727
2728 // returns pointer to some fancy row 'below' specified row
2729 RowList::iterator LyXText::cursorIRow() const
2730 {
2731         int y = 0;
2732         return getRow(cursor.par(), cursor.pos(), y);
2733 }
2734
2735
2736 RowList::iterator LyXText::getRowNearY(int & y) const
2737 {
2738         RowList::iterator rit = anchor_row_;
2739         RowList::iterator const beg = rows().begin();
2740         RowList::iterator const end = rows().end();
2741
2742         if (rows().empty()) {
2743                 y = 0;
2744                 return end;
2745         }
2746         if (rit == end)
2747                 rit = beg;
2748
2749         int tmpy = rit->y();
2750
2751         if (tmpy <= y) {
2752                 while (rit != end && tmpy <= y) {
2753                         tmpy += rit->height();
2754                         ++rit;
2755                 }
2756                 if (rit != beg) {
2757                         --rit;
2758                         tmpy -= rit->height();
2759                 }
2760         } else {
2761                 while (rit != beg && tmpy > y) {
2762                         --rit;
2763                         tmpy -= rit->height();
2764                 }
2765         }
2766         if (tmpy < 0 || rit == end) {
2767                 tmpy = 0;
2768                 rit = beg;
2769         }
2770
2771         // return the rel y
2772         y = tmpy;
2773
2774         return rit;
2775 }
2776
2777
2778 int LyXText::getDepth() const
2779 {
2780         return cursor.par()->getDepth();
2781 }