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