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