]> git.lyx.org Git - lyx.git/blob - src/text.C
* lfuns.h: new LFUN_REPEAT, LFUN_INSERT_LINE, LFUN_INSERT_PAGEBREAK
[lyx.git] / src / text.C
1 /**
2  * \file src/text.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Asger Alstrup
7  * \author Lars Gullik Bjønnes
8  * \author Jean-Marc Lasgouttes
9  * \author John Levon
10  * \author André Pönitz
11  * \author Dekel Tsur
12  * \author Jürgen Vigna
13  *
14  * Full author contact details are available in file CREDITS.
15  */
16
17 #include <config.h>
18
19 #include "lyxtext.h"
20
21 #include "buffer.h"
22 #include "bufferparams.h"
23 #include "BufferView.h"
24 #include "debug.h"
25 #include "encoding.h"
26 #include "funcrequest.h"
27 #include "gettext.h"
28 #include "language.h"
29 #include "LColor.h"
30 #include "lyxlength.h"
31 #include "lyxrc.h"
32 #include "lyxrow.h"
33 #include "lyxrow_funcs.h"
34 #include "metricsinfo.h"
35 #include "paragraph.h"
36 #include "paragraph_funcs.h"
37 #include "ParagraphParameters.h"
38 #include "rowpainter.h"
39 #include "text_funcs.h"
40 #include "undo.h"
41 #include "vspace.h"
42 #include "WordLangTuple.h"
43
44 #include "frontends/font_metrics.h"
45 #include "frontends/LyXView.h"
46
47 #include "insets/insettext.h"
48
49 #include "support/lstrings.h"
50 #include "support/textutils.h"
51
52 using bv_funcs::number;
53
54 using lyx::pos_type;
55 using lyx::word_location;
56
57 using lyx::support::contains;
58 using lyx::support::lowercase;
59 using lyx::support::uppercase;
60
61 using std::max;
62 using std::endl;
63 using std::string;
64
65
66 /// top, right, bottom pixel margin
67 extern int const PAPER_MARGIN = 20;
68 /// margin for changebar
69 extern int const CHANGEBAR_MARGIN = 10;
70 /// left margin
71 extern int const LEFT_MARGIN = PAPER_MARGIN + CHANGEBAR_MARGIN;
72
73
74
75 int bibitemMaxWidth(BufferView *, LyXFont const &);
76
77
78 namespace {
79
80 unsigned int maxParagraphWidth(ParagraphList const & plist)
81 {
82         unsigned int width = 0;
83         ParagraphList::const_iterator pit = plist.begin();
84         ParagraphList::const_iterator end = plist.end();
85                 for (; pit != end; ++pit)
86                         width = std::max(width, pit->width);
87         return width;
88 }
89
90 } // namespace anon
91
92
93 BufferView * LyXText::bv()
94 {
95         BOOST_ASSERT(bv_owner != 0);
96         return bv_owner;
97 }
98
99
100 BufferView * LyXText::bv() const
101 {
102         BOOST_ASSERT(bv_owner != 0);
103         return bv_owner;
104 }
105
106
107 void LyXText::updateRowPositions()
108 {
109         ParagraphList::iterator pit = ownerParagraphs().begin();
110         ParagraphList::iterator end = ownerParagraphs().end();
111         for (height = 0; pit != end; ++pit) {
112                 pit->y = height;
113                 height += pit->height;
114         }
115 }
116
117
118 int LyXText::workWidth() const
119 {
120         return inset_owner ? inset_owner->textWidth() : bv()->workWidth();
121 }
122
123
124 int LyXText::getRealCursorX() const
125 {
126         int x = cursor.x();
127         if (the_locking_inset && the_locking_inset->getLyXText(bv()) != this)
128                 x = the_locking_inset->getLyXText(bv())->getRealCursorX();
129         return x;
130 }
131
132
133 // This is the comments that some of the warnings below refers to.
134 // There are some issues in this file and I don't think they are
135 // really related to the FIX_DOUBLE_SPACE patch. I'd rather think that
136 // this is a problem that has been here almost from day one and that a
137 // larger userbase with different access patters triggers the bad
138 // behaviour. (segfaults.) What I think happen is: In several places
139 // we store the paragraph in the current cursor and then moves the
140 // cursor. This movement of the cursor will delete paragraph at the
141 // old position if it is now empty. This will make the temporary
142 // pointer to the old cursor paragraph invalid and dangerous to use.
143 // And is some cases this will trigger a segfault. I have marked some
144 // of the cases where this happens with a warning, but I am sure there
145 // are others in this file and in text2.C. There is also a note in
146 // Delete() that you should read. In Delete I store the paragraph->id
147 // instead of a pointer to the paragraph. I am pretty sure this faulty
148 // use of temporary pointers to paragraphs that might have gotten
149 // invalidated (through a cursor movement) before they are used, are
150 // the cause of the strange crashes we get reported often.
151 //
152 // It is very tiresom to change this code, especially when it is as
153 // hard to read as it is. Help to fix all the cases where this is done
154 // would be greately appreciated.
155 //
156 // Lgb
157
158 int LyXText::singleWidth(ParagraphList::iterator pit, pos_type pos) const
159 {
160         if (pos >= pit->size())
161                 return 0;
162
163         char const c = pit->getChar(pos);
164         LyXFont const & font = getFont(pit, pos);
165         return singleWidth(pit, pos, c, font);
166 }
167
168
169 int LyXText::singleWidth(ParagraphList::iterator pit,
170                          pos_type pos, char c, LyXFont const & font) const
171 {
172         if (pos >= pit->size()) {
173                 lyxerr << "in singleWidth(), pos: " << pos << endl;
174                 BOOST_ASSERT(false);
175                 return 0;
176         }
177
178
179         // The most common case is handled first (Asger)
180         if (IsPrintable(c)) {
181                 if (!font.language()->RightToLeft()) {
182                         if ((lyxrc.font_norm_type == LyXRC::ISO_8859_6_8 ||
183                              lyxrc.font_norm_type == LyXRC::ISO_10646_1)
184                             && font.language()->lang() == "arabic") {
185                                 if (Encodings::IsComposeChar_arabic(c))
186                                         return 0;
187                                 else
188                                         c = pit->transformChar(c, pos);
189                         } else if (font.language()->lang() == "hebrew" &&
190                                  Encodings::IsComposeChar_hebrew(c))
191                                 return 0;
192                 }
193                 return font_metrics::width(c, font);
194         }
195
196         if (c == Paragraph::META_INSET) {
197                 InsetOld * tmpinset = pit->getInset(pos);
198                 BOOST_ASSERT(tmpinset);
199                 if (tmpinset->lyxCode() == InsetOld::HFILL_CODE) {
200                         // Because of the representation as vertical lines
201                         return 3;
202                 }
203                 return tmpinset->width();
204         }
205
206         if (IsSeparatorChar(c))
207                 c = ' ';
208         return font_metrics::width(c, font);
209 }
210
211
212 int LyXText::leftMargin(ParagraphList::iterator pit, Row const & row) const
213 {
214         LyXTextClass const & tclass =
215                 bv()->buffer()->params().getLyXTextClass();
216         LyXLayout_ptr const & layout = pit->layout();
217
218         string parindent = layout->parindent;
219
220         int x = LEFT_MARGIN;
221
222         x += font_metrics::signedWidth(tclass.leftmargin(), tclass.defaultfont());
223
224         // this is the way, LyX handles the LaTeX-Environments.
225         // I have had this idea very late, so it seems to be a
226         // later added hack and this is true
227         if (!pit->getDepth()) {
228                 if (pit->layout() == tclass.defaultLayout()) {
229                         // find the previous same level paragraph
230                         if (pit != ownerParagraphs().begin()) {
231                                 ParagraphList::iterator newpit =
232                                         depthHook(pit, ownerParagraphs(),
233                                                   pit->getDepth());
234                                 if (newpit == pit &&
235                                     newpit->layout()->nextnoindent)
236                                         parindent.erase();
237                         }
238                 }
239         } else {
240                 // find the next level paragraph
241
242                 ParagraphList::iterator newpar = outerHook(pit,
243                                                            ownerParagraphs());
244
245                 // make a corresponding row. Needed to call leftMargin()
246
247                 // check wether it is a sufficent paragraph
248                 if (newpar != ownerParagraphs().end() &&
249                     newpar->layout()->isEnvironment()) {
250                         x = leftMargin(newpar, Row(newpar->size()));
251                 }
252
253                 if (newpar != ownerParagraphs().end() &&
254                     pit->layout() == tclass.defaultLayout()) {
255                         if (newpar->params().noindent())
256                                 parindent.erase();
257                         else {
258                                 parindent = newpar->layout()->parindent;
259                         }
260
261                 }
262         }
263
264         LyXFont const labelfont = getLabelFont(pit);
265         switch (layout->margintype) {
266         case MARGIN_DYNAMIC:
267                 if (!layout->leftmargin.empty()) {
268                         x += font_metrics::signedWidth(layout->leftmargin,
269                                                   tclass.defaultfont());
270                 }
271                 if (!pit->getLabelstring().empty()) {
272                         x += font_metrics::signedWidth(layout->labelindent,
273                                                   labelfont);
274                         x += font_metrics::width(pit->getLabelstring(),
275                                             labelfont);
276                         x += font_metrics::width(layout->labelsep, labelfont);
277                 }
278                 break;
279         case MARGIN_MANUAL:
280                 x += font_metrics::signedWidth(layout->labelindent, labelfont);
281                 // The width of an empty par, even with manual label, should be 0
282                 if (!pit->empty() && row.pos() >= pit->beginningOfBody()) {
283                         if (!pit->getLabelWidthString().empty()) {
284                                 x += font_metrics::width(pit->getLabelWidthString(),
285                                                labelfont);
286                                 x += font_metrics::width(layout->labelsep, labelfont);
287                         }
288                 }
289                 break;
290         case MARGIN_STATIC:
291                 x += font_metrics::signedWidth(layout->leftmargin, tclass.defaultfont()) * 4
292                         / (pit->getDepth() + 4);
293                 break;
294         case MARGIN_FIRST_DYNAMIC:
295                 if (layout->labeltype == LABEL_MANUAL) {
296                         if (row.pos() >= pit->beginningOfBody()) {
297                                 x += font_metrics::signedWidth(layout->leftmargin,
298                                                           labelfont);
299                         } else {
300                                 x += font_metrics::signedWidth(layout->labelindent,
301                                                           labelfont);
302                         }
303                 } else if (row.pos()
304                            // Special case to fix problems with
305                            // theorems (JMarc)
306                            || (layout->labeltype == LABEL_STATIC
307                                && layout->latextype == LATEX_ENVIRONMENT
308                                && !isFirstInSequence(pit, ownerParagraphs()))) {
309                         x += font_metrics::signedWidth(layout->leftmargin,
310                                                   labelfont);
311                 } else if (layout->labeltype != LABEL_TOP_ENVIRONMENT
312                            && layout->labeltype != LABEL_BIBLIO
313                            && layout->labeltype !=
314                            LABEL_CENTERED_TOP_ENVIRONMENT) {
315                         x += font_metrics::signedWidth(layout->labelindent,
316                                                   labelfont);
317                         x += font_metrics::width(layout->labelsep, labelfont);
318                         x += font_metrics::width(pit->getLabelstring(),
319                                             labelfont);
320                 }
321                 break;
322
323         case MARGIN_RIGHT_ADDRESS_BOX:
324         {
325                 // ok, a terrible hack. The left margin depends on the widest
326                 // row in this paragraph.
327                 RowList::iterator rit = pit->rows.begin();
328                 RowList::iterator end = pit->rows.end();
329 #warning This is wrong.
330                 int minfill = workWidth() / 2;
331                 for ( ; rit != end; ++rit)
332                         if (rit->fill() < minfill)
333                                 minfill = rit->fill();
334                 x += font_metrics::signedWidth(layout->leftmargin,
335                         tclass.defaultfont());
336                 x += minfill;
337         }
338         break;
339         }
340
341         if (workWidth() > 0 && !pit->params().leftIndent().zero()) {
342                 LyXLength const len = pit->params().leftIndent();
343                 int const tw = inset_owner ?
344                         inset_owner->latexTextWidth(bv()) : workWidth();
345                 x += len.inPixels(tw);
346         }
347
348         LyXAlignment align;
349
350         if (pit->params().align() == LYX_ALIGN_LAYOUT)
351                 align = layout->align;
352         else
353                 align = pit->params().align();
354
355         // set the correct parindent
356         if (row.pos() == 0) {
357                 if ((layout->labeltype == LABEL_NO_LABEL
358                      || layout->labeltype == LABEL_TOP_ENVIRONMENT
359                      || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT
360                      || (layout->labeltype == LABEL_STATIC
361                          && layout->latextype == LATEX_ENVIRONMENT
362                          && !isFirstInSequence(pit, ownerParagraphs())))
363                     && align == LYX_ALIGN_BLOCK
364                     && !pit->params().noindent()
365                         // in tabulars and ert paragraphs are never indented!
366                         && (!pit->inInset() || !pit->inInset()->owner() ||
367                                 (pit->inInset()->owner()->lyxCode() != InsetOld::TABULAR_CODE &&
368                                  pit->inInset()->owner()->lyxCode() != InsetOld::ERT_CODE))
369                     && (pit->layout() != tclass.defaultLayout() ||
370                         bv()->buffer()->params().paragraph_separation ==
371                         BufferParams::PARSEP_INDENT)) {
372                         x += font_metrics::signedWidth(parindent,
373                                                   tclass.defaultfont());
374                 } else if (layout->labeltype == LABEL_BIBLIO) {
375                         // ale970405 Right width for bibitems
376                         x += bibitemMaxWidth(bv(), tclass.defaultfont());
377                 }
378         }
379
380         return x;
381 }
382
383
384 int LyXText::rightMargin(Paragraph const & par,
385         Buffer const & buf, Row const &) const
386 {
387         LyXTextClass const & tclass = buf.params().getLyXTextClass();
388         LyXLayout_ptr const & layout = par.layout();
389
390         return PAPER_MARGIN
391                 + font_metrics::signedWidth(tclass.rightmargin(),
392                                        tclass.defaultfont())
393                 + font_metrics::signedWidth(layout->rightmargin,
394                                        tclass.defaultfont())
395                 * 4 / (par.getDepth() + 4);
396 }
397
398
399 int LyXText::labelEnd(ParagraphList::iterator pit, Row const & row) const
400 {
401         if (pit->layout()->margintype == MARGIN_MANUAL) {
402                 Row tmprow = row;
403                 tmprow.pos(pit->size());
404                 // return the beginning of the body
405                 return leftMargin(pit, tmprow);
406         }
407
408         // LabelEnd is only needed if the layout
409         // fills a flushleft label.
410         return 0;
411 }
412
413
414 namespace {
415
416 // this needs special handling - only newlines count as a break point
417 pos_type addressBreakPoint(pos_type i, Paragraph const & par)
418 {
419         pos_type const end = par.size();
420         
421         for (; i < end; ++i)
422                 if (par.isNewline(i))
423                         return i + 1;
424
425         return end;
426 }
427
428 };
429
430
431 void LyXText::rowBreakPoint(ParagraphList::iterator pit, Row & row) const
432 {
433         pos_type const end = pit->size();
434         pos_type const pos = row.pos();
435         if (pos == end) {
436                 row.endpos(end);
437                 return;
438         }
439         
440         // maximum pixel width of a row.
441         int width = workWidth()
442                 - rightMargin(*pit, *bv()->buffer(), row);
443 //              - leftMargin(pit, row);
444
445         // inset->textWidth() returns -1 via workWidth(),
446         // but why ?
447         if (width < 0) {
448                 row.endpos(end);
449                 return;
450         }
451
452         LyXLayout_ptr const & layout = pit->layout();
453
454         if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX) {
455                 row.endpos(addressBreakPoint(pos, *pit));
456                 return;
457         }
458
459         pos_type const body_pos = pit->beginningOfBody();
460
461
462         // Now we iterate through until we reach the right margin
463         // or the end of the par, then choose the possible break
464         // nearest that.
465
466         int const left = leftMargin(pit, row);
467         int x = left;
468
469         // pixel width since last breakpoint
470         int chunkwidth = 0;
471
472
473         // We re-use the font resolution for the entire font span when possible
474         LyXFont font = getFont(pit, pos);
475         lyx::pos_type endPosOfFontSpan = pit->getEndPosOfFontSpan(pos);
476
477         pos_type point = end;
478         pos_type i = pos;
479         for ( ; i < end; ++i) {
480                 if (pit->isNewline(i)) {
481                         point = i + 1;
482                         break;
483                 }
484                 // Break before...      
485                 if (i + 1 < end) {
486                         InsetOld * in = pit->getInset(i + 1);
487                         if (in && in->display()) {
488                                 point = i + 1;
489                                 break;
490                         }
491                         // ...and after.
492                         in = pit->getInset(i);
493                         if (in && in->display()) {
494                                 point = i + 1;
495                                 break;
496                         }
497                 }
498
499                 char const c = pit->getChar(i);
500  
501                 if (i > endPosOfFontSpan) {
502                         font = getFont(pit, i);
503                         endPosOfFontSpan = pit->getEndPosOfFontSpan(i);
504                 }
505                 
506                 {
507                         int thiswidth = singleWidth(pit, i, c, font);
508
509                         // add the auto-hfill from label end to the body
510                         if (body_pos && i == body_pos) {
511                                 int add = font_metrics::width(layout->labelsep, getLabelFont(pit));
512                                 if (pit->isLineSeparator(i - 1))
513                                         add -= singleWidth(pit, i - 1);
514
515                                 add = std::max(add, labelEnd(pit, row) - x);
516                                 thiswidth += add;
517                         }
518
519                         x += thiswidth;
520                         //lyxerr << "i: " << i << " x: "
521                         //<< x << " width: " << width << endl;
522                         chunkwidth += thiswidth;
523                 }
524                 
525
526                 // break before a character that will fall off
527                 // the right of the row
528                 if (x >= width) {
529                         // if no break before, break here
530                         if (point == end || chunkwidth >= width - left) {
531                                 if (i > pos) {
532                                         point = i;
533                                         break;  
534                                 }
535                         }
536                         // exit on last registered breakpoint:
537                         if (i + 1 < end)
538                                 break;
539                 }
540
541                 InsetOld * in = pit->getInset(i);
542                 if (!in || in->isChar()) {
543                         // some insets are line separators too
544                         if (pit->isLineSeparator(i)) {
545                                 // register breakpoint:
546                                 point = i + 1; 
547                                 chunkwidth = 0;
548                         }
549                 }
550         }
551
552         if (point == end && i != end && x >= width) {
553                 // didn't find one, break at the point we reached the edge
554                 point = i + 1;
555         } else if (i == end && x < width) {
556                 // maybe found one, but the par is short enough.
557                 point = end;
558         }
559
560         // manual labels cannot be broken in LaTeX. But we
561         // want to make our on-screen rendering of footnotes
562         // etc. still break
563         if (body_pos && point < body_pos)
564                 point = body_pos;
565
566         row.endpos(point);
567 }
568
569
570 // returns the minimum space a row needs on the screen in pixel
571 void LyXText::fill(ParagraphList::iterator pit, Row & row, int paper_width) const
572 {
573         int w;
574         // get the pure distance
575         pos_type const end = row.endpos();
576
577         LyXLayout_ptr const & layout = pit->layout();
578
579         // special handling of the right address boxes
580 #if 0
581 //this is not working anymore
582         if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX) {
583                 int const tmpfill = row.fill();
584                 row.fill(0); // the minfill in leftMargin()
585                 w = leftMargin(pit, row);
586                 row.fill(tmpfill);
587         } else {
588                 w = leftMargin(pit, row);
589         }
590 #else
591         w = leftMargin(pit, row);
592 #endif
593
594         pos_type const body_pos = pit->beginningOfBody();
595         pos_type i = row.pos();
596
597         if (i < end) {
598                 // We re-use the font resolution for the entire span when possible
599                 LyXFont font = getFont(pit, i);
600                 lyx::pos_type endPosOfFontSpan = pit->getEndPosOfFontSpan(i);
601                 while (i < end) {
602                         if (body_pos > 0 && i == body_pos) {
603                                 w += font_metrics::width(layout->labelsep, getLabelFont(pit));
604                                 if (pit->isLineSeparator(i - 1))
605                                         w -= singleWidth(pit, i - 1);
606                                 int left_margin = labelEnd(pit, row);
607                                 if (w < left_margin)
608                                         w = left_margin;
609                         }
610                         char const c = pit->getChar(i);
611                         if (IsPrintable(c) && i > endPosOfFontSpan) {
612                                 // We need to get the next font
613                                 font = getFont(pit, i);
614                                 endPosOfFontSpan = pit->getEndPosOfFontSpan(i);
615                         }
616                         w += singleWidth(pit, i, c, font);
617                         ++i;
618                 }
619         }
620         if (body_pos > 0 && body_pos >= end) {
621                 w += font_metrics::width(layout->labelsep, getLabelFont(pit));
622                 if (end > 0 && pit->isLineSeparator(end - 1))
623                         w -= singleWidth(pit, end - 1);
624                 int const left_margin = labelEnd(pit, row);
625                 if (w < left_margin)
626                         w = left_margin;
627         }
628
629         int const fill = paper_width - w - rightMargin(*pit, *bv()->buffer(), row);
630         row.fill(fill);
631         row.width(paper_width - fill);
632 }
633
634
635 // returns the minimum space a manual label needs on the screen in pixel
636 int LyXText::labelFill(ParagraphList::iterator pit, Row const & row) const
637 {
638         pos_type last = pit->beginningOfBody();
639
640         BOOST_ASSERT(last > 0);
641
642         // -1 because a label ends with a space that is in the label
643         --last;
644
645         // a separator at this end does not count
646         if (pit->isLineSeparator(last))
647                 --last;
648
649         int w = 0;
650         for (pos_type i = row.pos(); i <= last; ++i)
651                 w += singleWidth(pit, i);
652
653         int fill = 0;
654         string const & labwidstr = pit->params().labelWidthString();
655         if (!labwidstr.empty()) {
656                 LyXFont const labfont = getLabelFont(pit);
657                 int const labwidth = font_metrics::width(labwidstr, labfont);
658                 fill = max(labwidth - w, 0);
659         }
660
661         return fill;
662 }
663
664
665 LColor_color LyXText::backgroundColor() const
666 {
667         if (inset_owner)
668                 return inset_owner->backgroundColor();
669         else
670                 return LColor::background;
671 }
672
673
674 void LyXText::setHeightOfRow(ParagraphList::iterator pit, Row & row)
675 {
676         // get the maximum ascent and the maximum descent
677         double layoutasc = 0;
678         double layoutdesc = 0;
679         double tmptop = 0;
680
681         // ok, let us initialize the maxasc and maxdesc value.
682         // Only the fontsize count. The other properties
683         // are taken from the layoutfont. Nicer on the screen :)
684         LyXLayout_ptr const & layout = pit->layout();
685
686         // as max get the first character of this row then it can increase but not
687         // decrease the height. Just some point to start with so we don't have to
688         // do the assignment below too often.
689         LyXFont font = getFont(pit, row.pos());
690         LyXFont::FONT_SIZE const tmpsize = font.size();
691         font = getLayoutFont(pit);
692         LyXFont::FONT_SIZE const size = font.size();
693         font.setSize(tmpsize);
694
695         LyXFont labelfont = getLabelFont(pit);
696
697         double spacing_val = 1.0;
698         if (!pit->params().spacing().isDefault())
699                 spacing_val = pit->params().spacing().getValue();
700         else
701                 spacing_val = bv()->buffer()->params().spacing().getValue();
702         //lyxerr << "spacing_val = " << spacing_val << endl;
703
704         // these are minimum values
705         int maxasc  = int(font_metrics::maxAscent(font) *
706                           layout->spacing.getValue() * spacing_val);
707         int maxdesc = int(font_metrics::maxDescent(font) *
708                           layout->spacing.getValue() * spacing_val);
709
710         // insets may be taller
711         InsetList::iterator ii = pit->insetlist.begin();
712         InsetList::iterator iend = pit->insetlist.end();
713         for ( ; ii != iend; ++ii) {
714                 if (ii->pos >= row.pos() && ii->pos < row.endpos()) {
715                         maxasc = max(maxasc, ii->inset->ascent());
716                         maxdesc = max(maxdesc, ii->inset->descent());
717                 }
718         }
719
720         // Check if any custom fonts are larger (Asger)
721         // This is not completely correct, but we can live with the small,
722         // cosmetic error for now.
723         int labeladdon = 0;
724         pos_type const pos_end = row.endpos();
725
726         LyXFont::FONT_SIZE maxsize =
727                 pit->highestFontInRange(row.pos(), pos_end, size);
728         if (maxsize > font.size()) {
729                 font.setSize(maxsize);
730                 maxasc = max(maxasc, font_metrics::maxAscent(font));
731                 maxdesc = max(maxdesc, font_metrics::maxDescent(font));
732         }
733
734         // This is nicer with box insets:
735         ++maxasc;
736         ++maxdesc;
737
738         row.ascent_of_text(maxasc);
739
740         // is it a top line?
741         if (!row.pos()) {
742                 BufferParams const & bufparams = bv()->buffer()->params();
743                 // some parksips VERY EASY IMPLEMENTATION
744                 if (bv()->buffer()->params().paragraph_separation ==
745                         BufferParams::PARSEP_SKIP)
746                 {
747                         if (layout->isParagraph()
748                                 && pit->getDepth() == 0
749                                 && pit != ownerParagraphs().begin())
750                         {
751                                 maxasc += bufparams.getDefSkip().inPixels(*bv());
752                         } else if (pit != ownerParagraphs().begin() &&
753                                    boost::prior(pit)->layout()->isParagraph() &&
754                                    boost::prior(pit)->getDepth() == 0)
755                         {
756                                 // is it right to use defskip here too? (AS)
757                                 maxasc += bufparams.getDefSkip().inPixels(*bv());
758                         }
759                 }
760
761                 // the top margin
762                 if (pit == ownerParagraphs().begin() && !isInInset())
763                         maxasc += PAPER_MARGIN;
764
765                 // add the vertical spaces, that the user added
766                 maxasc += getLengthMarkerHeight(*bv(), pit->params().spaceTop());
767
768                 if (pit->params().startOfAppendix())
769                         maxasc += 3 * defaultRowHeight();
770
771                 // This is special code for the chapter, since the label of this
772                 // layout is printed in an extra row
773                 if (layout->counter == "chapter" && bufparams.secnumdepth >= 0) {
774                         float spacing_val = 1.0;
775                         if (!pit->params().spacing().isDefault()) {
776                                 spacing_val = pit->params().spacing().getValue();
777                         } else {
778                                 spacing_val = bufparams.spacing().getValue();
779                         }
780
781                         labeladdon = int(font_metrics::maxDescent(labelfont) *
782                                          layout->spacing.getValue() *
783                                          spacing_val)
784                                 + int(font_metrics::maxAscent(labelfont) *
785                                       layout->spacing.getValue() *
786                                       spacing_val);
787                 }
788
789                 // special code for the top label
790                 if ((layout->labeltype == LABEL_TOP_ENVIRONMENT
791                      || layout->labeltype == LABEL_BIBLIO
792                      || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
793                     && isFirstInSequence(pit, ownerParagraphs())
794                     && !pit->getLabelstring().empty())
795                 {
796                         float spacing_val = 1.0;
797                         if (!pit->params().spacing().isDefault()) {
798                                 spacing_val = pit->params().spacing().getValue();
799                         } else {
800                                 spacing_val = bufparams.spacing().getValue();
801                         }
802
803                         labeladdon = int(
804                                 (font_metrics::maxAscent(labelfont) +
805                                  font_metrics::maxDescent(labelfont)) *
806                                   layout->spacing.getValue() *
807                                   spacing_val
808                                 + layout->topsep * defaultRowHeight()
809                                 + layout->labelbottomsep * defaultRowHeight());
810                 }
811
812                 // And now the layout spaces, for example before and after
813                 // a section, or between the items of a itemize or enumerate
814                 // environment.
815
816                 ParagraphList::iterator prev =
817                         depthHook(pit, ownerParagraphs(),
818                                         pit->getDepth());
819                 if (prev != pit && prev->layout() == layout &&
820                         prev->getDepth() == pit->getDepth() &&
821                         prev->getLabelWidthString() == pit->getLabelWidthString())
822                 {
823                         layoutasc = (layout->itemsep * defaultRowHeight());
824                 } else if (pit != ownerParagraphs().begin() || row.pos() != 0) {
825                         tmptop = layout->topsep;
826
827                         if (tmptop > 0)
828                                 layoutasc = (tmptop * defaultRowHeight());
829                 }
830
831                 prev = outerHook(pit, ownerParagraphs());
832                 if (prev != ownerParagraphs().end())  {
833                         maxasc += int(prev->layout()->parsep * defaultRowHeight());
834                 } else if (pit != ownerParagraphs().begin()) {
835                         ParagraphList::iterator prior_pit = boost::prior(pit);
836                         if (prior_pit->getDepth() != 0 ||
837                                         prior_pit->layout() == layout) {
838                                 maxasc += int(layout->parsep * defaultRowHeight());
839                         }
840                 }
841         }
842
843         // is it a bottom line?
844         if (row.endpos() >= pit->size()) {
845                 // the bottom margin
846                 ParagraphList::iterator nextpit = boost::next(pit);
847                 if (nextpit == ownerParagraphs().end() && !isInInset())
848                         maxdesc += PAPER_MARGIN;
849
850                 // add the vertical spaces, that the user added
851                 maxdesc += getLengthMarkerHeight(*bv(), pit->params().spaceBottom());
852
853                 // and now the layout spaces, for example before and after
854                 // a section, or between the items of a itemize or enumerate
855                 // environment
856                 if (nextpit != ownerParagraphs().end()) {
857                         ParagraphList::iterator comparepit = pit;
858                         float usual = 0;
859                         float unusual = 0;
860
861                         if (comparepit->getDepth() > nextpit->getDepth()) {
862                                 usual = (comparepit->layout()->bottomsep * defaultRowHeight());
863                                 comparepit = depthHook(comparepit, ownerParagraphs(), nextpit->getDepth());
864                                 if (comparepit->layout()!= nextpit->layout()
865                                         || nextpit->getLabelWidthString() !=
866                                         comparepit->getLabelWidthString())
867                                 {
868                                         unusual = (comparepit->layout()->bottomsep * defaultRowHeight());
869                                 }
870                                 if (unusual > usual)
871                                         layoutdesc = unusual;
872                                 else
873                                         layoutdesc = usual;
874                         } else if (comparepit->getDepth() ==  nextpit->getDepth()) {
875
876                                 if (comparepit->layout() != nextpit->layout()
877                                         || nextpit->getLabelWidthString() !=
878                                         comparepit->getLabelWidthString())
879                                         layoutdesc = int(comparepit->layout()->bottomsep * defaultRowHeight());
880                         }
881                 }
882         }
883
884         // incalculate the layout spaces
885         maxasc += int(layoutasc * 2 / (2 + pit->getDepth()));
886         maxdesc += int(layoutdesc * 2 / (2 + pit->getDepth()));
887
888         row.height(maxasc + maxdesc + labeladdon);
889         row.baseline(maxasc + labeladdon);
890         row.top_of_text(row.baseline() - font_metrics::maxAscent(font));
891 }
892
893
894 void LyXText::breakParagraph(ParagraphList & paragraphs, char keep_layout)
895 {
896         // allow only if at start or end, or all previous is new text
897         ParagraphList::iterator cpit = cursorPar();
898         if (cursor.pos() && cursor.pos() != cpit->size()
899             && cpit->isChangeEdited(0, cursor.pos()))
900                 return;
901
902         LyXTextClass const & tclass =
903                 bv()->buffer()->params().getLyXTextClass();
904         LyXLayout_ptr const & layout = cpit->layout();
905
906         // this is only allowed, if the current paragraph is not empty or caption
907         // and if it has not the keepempty flag active
908         if (cpit->empty() && !cpit->allowEmpty()
909            && layout->labeltype != LABEL_SENSITIVE)
910                 return;
911
912         recUndo(cursor.par());
913
914         // Always break behind a space
915         //
916         // It is better to erase the space (Dekel)
917         if (cursor.pos() < cpit->size() && cpit->isLineSeparator(cursor.pos()))
918            cpit->erase(cursor.pos());
919
920         // break the paragraph
921         if (keep_layout)
922                 keep_layout = 2;
923         else
924                 keep_layout = layout->isEnvironment();
925
926         // we need to set this before we insert the paragraph. IMO the
927         // breakParagraph call should return a bool if it inserts the
928         // paragraph before or behind and we should react on that one
929         // but we can fix this in 1.3.0 (Jug 20020509)
930         bool const isempty = cpit->allowEmpty() && cpit->empty();
931         ::breakParagraph(bv()->buffer()->params(), paragraphs, cpit,
932                          cursor.pos(), keep_layout);
933
934 #warning Trouble Point! (Lgb)
935         // When ::breakParagraph is called from within an inset we must
936         // ensure that the correct ParagraphList is used. Today that is not
937         // the case and the Buffer::paragraphs is used. Not good. (Lgb)
938         cpit = cursorPar();
939         ParagraphList::iterator next_par = boost::next(cpit);
940
941         // well this is the caption hack since one caption is really enough
942         if (layout->labeltype == LABEL_SENSITIVE) {
943                 if (!cursor.pos())
944                         // set to standard-layout
945                         cpit->applyLayout(tclass.defaultLayout());
946                 else
947                         // set to standard-layout
948                         next_par->applyLayout(tclass.defaultLayout());
949         }
950
951         // if the cursor is at the beginning of a row without prior newline,
952         // move one row up!
953         // This touches only the screen-update. Otherwise we would may have
954         // an empty row on the screen
955         RowList::iterator crit = cpit->getRow(cursor.pos());
956         if (cursor.pos() && crit->pos() == cursor.pos()
957             && !cpit->isNewline(cursor.pos() - 1))
958         {
959                 cursorLeft(bv());
960         }
961
962         while (!next_par->empty() && next_par->isNewline(0))
963                 next_par->erase(0);
964
965         updateCounters();
966         redoParagraph(cpit);
967         redoParagraph(next_par);
968
969         // This check is necessary. Otherwise the new empty paragraph will
970         // be deleted automatically. And it is more friendly for the user!
971         if (cursor.pos() || isempty)
972                 setCursor(next_par, 0);
973         else
974                 setCursor(cpit, 0);
975 }
976
977
978 // convenience function
979 void LyXText::redoParagraph()
980 {
981         clearSelection();
982         redoParagraph(cursorPar());
983         setCursorIntern(cursor.par(), cursor.pos());
984 }
985
986
987 // insert a character, moves all the following breaks in the
988 // same Paragraph one to the right and make a rebreak
989 void LyXText::insertChar(char c)
990 {
991         recordUndo(Undo::INSERT, this, cursor.par(), cursor.par());
992
993         // When the free-spacing option is set for the current layout,
994         // disable the double-space checking
995
996         bool const freeSpacing = cursorPar()->layout()->free_spacing ||
997                 cursorPar()->isFreeSpacing();
998
999         if (lyxrc.auto_number) {
1000                 static string const number_operators = "+-/*";
1001                 static string const number_unary_operators = "+-";
1002                 static string const number_seperators = ".,:";
1003
1004                 if (current_font.number() == LyXFont::ON) {
1005                         if (!IsDigit(c) && !contains(number_operators, c) &&
1006                             !(contains(number_seperators, c) &&
1007                               cursor.pos() >= 1 &&
1008                               cursor.pos() < cursorPar()->size() &&
1009                               getFont(cursorPar(), cursor.pos()).number() == LyXFont::ON &&
1010                               getFont(cursorPar(), cursor.pos() - 1).number() == LyXFont::ON)
1011                            )
1012                                 number(bv()); // Set current_font.number to OFF
1013                 } else if (IsDigit(c) &&
1014                            real_current_font.isVisibleRightToLeft()) {
1015                         number(bv()); // Set current_font.number to ON
1016
1017                         if (cursor.pos() > 0) {
1018                                 char const c = cursorPar()->getChar(cursor.pos() - 1);
1019                                 if (contains(number_unary_operators, c) &&
1020                                     (cursor.pos() == 1 ||
1021                                      cursorPar()->isSeparator(cursor.pos() - 2) ||
1022                                      cursorPar()->isNewline(cursor.pos() - 2))
1023                                   ) {
1024                                         setCharFont(
1025                                                     cursorPar(),
1026                                                     cursor.pos() - 1,
1027                                                     current_font);
1028                                 } else if (contains(number_seperators, c) &&
1029                                            cursor.pos() >= 2 &&
1030                                            getFont(
1031                                                    cursorPar(),
1032                                                    cursor.pos() - 2).number() == LyXFont::ON) {
1033                                         setCharFont(
1034                                                     cursorPar(),
1035                                                     cursor.pos() - 1,
1036                                                     current_font);
1037                                 }
1038                         }
1039                 }
1040         }
1041
1042
1043         // First check, if there will be two blanks together or a blank at
1044         // the beginning of a paragraph.
1045         // I decided to handle blanks like normal characters, the main
1046         // difference are the special checks when calculating the row.fill
1047         // (blank does not count at the end of a row) and the check here
1048
1049         // The bug is triggered when we type in a description environment:
1050         // The current_font is not changed when we go from label to main text
1051         // and it should (along with realtmpfont) when we type the space.
1052         // CHECK There is a bug here! (Asger)
1053
1054         // store the current font.  This is because of the use of cursor
1055         // movements. The moving cursor would refresh the current font
1056         LyXFont realtmpfont = real_current_font;
1057         LyXFont rawtmpfont = current_font;
1058
1059         if (!freeSpacing && IsLineSeparatorChar(c)) {
1060                 if ((cursor.pos() > 0
1061                      && cursorPar()->isLineSeparator(cursor.pos() - 1))
1062                     || (cursor.pos() > 0
1063                         && cursorPar()->isNewline(cursor.pos() - 1))
1064                     || (cursor.pos() == 0)) {
1065                         static bool sent_space_message = false;
1066                         if (!sent_space_message) {
1067                                 if (cursor.pos() == 0)
1068                                         bv()->owner()->message(_("You cannot insert a space at the beginning of a paragraph. Please read the Tutorial."));
1069                                 else
1070                                         bv()->owner()->message(_("You cannot type two spaces this way. Please read the Tutorial."));
1071                                 sent_space_message = true;
1072                         }
1073                         charInserted();
1074                         return;
1075                 }
1076         }
1077
1078         // Here case LyXText::InsertInset already inserted the character
1079         if (c != Paragraph::META_INSET)
1080                 cursorPar()->insertChar(cursor.pos(), c);
1081
1082         setCharFont(cursorPar(), cursor.pos(), rawtmpfont);
1083
1084         current_font = rawtmpfont;
1085         real_current_font = realtmpfont;
1086         redoParagraph(cursorPar());
1087         setCursor(cursor.par(), cursor.pos() + 1, false, cursor.boundary());
1088
1089         charInserted();
1090 }
1091
1092
1093 void LyXText::charInserted()
1094 {
1095         // Here we call finishUndo for every 20 characters inserted.
1096         // This is from my experience how emacs does it. (Lgb)
1097         static unsigned int counter;
1098         if (counter < 20) {
1099                 ++counter;
1100         } else {
1101                 finishUndo();
1102                 counter = 0;
1103         }
1104 }
1105
1106
1107 void LyXText::prepareToPrint(ParagraphList::iterator pit, Row & row) const
1108 {
1109         double w = row.fill();
1110         double fill_hfill = 0;
1111         double fill_label_hfill = 0;
1112         double fill_separator = 0;
1113         double x = 0;
1114
1115         bool const is_rtl =
1116                 pit->isRightToLeftPar(bv()->buffer()->params());
1117         if (is_rtl)
1118                 x = workWidth() > 0 ? rightMargin(*pit, *bv()->buffer(), row) : 0;
1119         else
1120                 x = workWidth() > 0 ? leftMargin(pit, row) : 0;
1121
1122         // is there a manual margin with a manual label
1123         LyXLayout_ptr const & layout = pit->layout();
1124
1125         if (layout->margintype == MARGIN_MANUAL
1126             && layout->labeltype == LABEL_MANUAL) {
1127                 /// We might have real hfills in the label part
1128                 int nlh = numberOfLabelHfills(*pit, row);
1129
1130                 // A manual label par (e.g. List) has an auto-hfill
1131                 // between the label text and the body of the
1132                 // paragraph too.
1133                 // But we don't want to do this auto hfill if the par
1134                 // is empty.
1135                 if (!pit->empty())
1136                         ++nlh;
1137
1138                 if (nlh && !pit->getLabelWidthString().empty())
1139                         fill_label_hfill = labelFill(pit, row) / double(nlh);
1140         }
1141
1142         // are there any hfills in the row?
1143         int const nh = numberOfHfills(*pit, row);
1144
1145         if (nh) {
1146                 if (w > 0)
1147                         fill_hfill = w / nh;
1148         // we don't have to look at the alignment if it is ALIGN_LEFT and
1149         // if the row is already larger then the permitted width as then
1150         // we force the LEFT_ALIGN'edness!
1151         } else if (int(row.width()) < workWidth()) {
1152                 // is it block, flushleft or flushright?
1153                 // set x how you need it
1154                 int align;
1155                 if (pit->params().align() == LYX_ALIGN_LAYOUT) {
1156                         align = layout->align;
1157                 } else {
1158                         align = pit->params().align();
1159                 }
1160                 // ERT insets should always be LEFT ALIGNED on screen
1161                 InsetOld * inset = pit->inInset();
1162                 if (inset && inset->owner() &&
1163                         inset->owner()->lyxCode() == InsetOld::ERT_CODE)
1164                 {
1165                         align = LYX_ALIGN_LEFT;
1166                 }
1167
1168                 // Display-style insets should always be on a centred row
1169                 // The test on pit->size() is to catch zero-size pars, which
1170                 // would trigger the assert in Paragraph::getInset().
1171                 //inset = pit->size() ? pit->getInset(row.pos()) : 0;
1172                 if (!pit->empty()
1173                     && pit->isInset(row.pos())
1174                     && pit->getInset(row.pos())->display())
1175                 {
1176                         align = LYX_ALIGN_CENTER;
1177                 }
1178                 
1179                 switch (align) {
1180             case LYX_ALIGN_BLOCK:
1181                 {
1182                         int const ns = numberOfSeparators(*pit, row);
1183                         bool disp_inset = false;
1184                         if (row.endpos() < pit->size()) {
1185                                 InsetOld * in = pit->getInset(row.endpos());
1186                                 if (in)
1187                                         disp_inset = in->display();
1188                         }
1189                         // If we have separators, this is not the last row of a
1190                         // par, does not end in newline, and is not row above a
1191                         // display inset... then stretch it
1192                         if (ns
1193                                 && row.endpos() < pit->size()
1194                                 && !pit->isNewline(row.endpos() - 1)
1195                                 && !disp_inset
1196                                 ) {
1197                                         fill_separator = w / ns;
1198                         } else if (is_rtl) {
1199                                 x += w;
1200                         }
1201                         break;
1202             }
1203             case LYX_ALIGN_RIGHT:
1204                         x += w;
1205                         break;
1206             case LYX_ALIGN_CENTER:
1207                         x += w / 2;
1208                         break;
1209                 }
1210         }
1211
1212         bidi.computeTables(*pit, *bv()->buffer(), row);
1213         if (is_rtl) {
1214                 pos_type body_pos = pit->beginningOfBody();
1215                 pos_type end = row.endpos();
1216
1217                 if (body_pos > 0 &&
1218                                 (body_pos > end ||
1219                                  !pit->isLineSeparator(body_pos - 1))) {
1220                         x += font_metrics::width(layout->labelsep, getLabelFont(pit));
1221                         if (body_pos <= end)
1222                                 x += fill_label_hfill;
1223                 }
1224         }
1225
1226         row.fill_hfill(fill_hfill);
1227         row.fill_label_hfill(fill_label_hfill);
1228         row.fill_separator(fill_separator);
1229         row.x(x);
1230 }
1231
1232
1233 // important for the screen
1234
1235
1236 // the cursor set functions have a special mechanism. When they
1237 // realize, that you left an empty paragraph, they will delete it.
1238 // They also delete the corresponding row
1239
1240 void LyXText::cursorRightOneWord()
1241 {
1242         ::cursorRightOneWord(*this, cursor, ownerParagraphs());
1243         setCursor(cursorPar(), cursor.pos());
1244 }
1245
1246
1247 // Skip initial whitespace at end of word and move cursor to *start*
1248 // of prior word, not to end of next prior word.
1249 void LyXText::cursorLeftOneWord()
1250 {
1251         LyXCursor tmpcursor = cursor;
1252         ::cursorLeftOneWord(*this, tmpcursor, ownerParagraphs());
1253         setCursor(getPar(tmpcursor), tmpcursor.pos());
1254 }
1255
1256
1257 void LyXText::selectWord(word_location loc)
1258 {
1259         LyXCursor from = cursor;
1260         LyXCursor to = cursor;
1261         ::getWord(*this, from, to, loc, ownerParagraphs());
1262         if (cursor != from)
1263                 setCursor(from.par(), from.pos());
1264         if (to == from)
1265                 return;
1266         selection.cursor = cursor;
1267         setCursor(to.par(), to.pos());
1268         setSelection();
1269 }
1270
1271
1272 // Select the word currently under the cursor when no
1273 // selection is currently set
1274 bool LyXText::selectWordWhenUnderCursor(word_location loc)
1275 {
1276         if (!selection.set()) {
1277                 selectWord(loc);
1278                 return selection.set();
1279         }
1280         return false;
1281 }
1282
1283
1284 void LyXText::acceptChange()
1285 {
1286         if (!selection.set() && cursorPar()->size())
1287                 return;
1288
1289         if (selection.start.par() == selection.end.par()) {
1290                 LyXCursor & startc = selection.start;
1291                 LyXCursor & endc = selection.end;
1292                 recordUndo(Undo::INSERT, this, startc.par());
1293                 getPar(startc)->acceptChange(startc.pos(), endc.pos());
1294                 finishUndo();
1295                 clearSelection();
1296                 redoParagraph(getPar(startc));
1297                 setCursorIntern(startc.par(), 0);
1298         }
1299 #warning handle multi par selection
1300 }
1301
1302
1303 void LyXText::rejectChange()
1304 {
1305         if (!selection.set() && cursorPar()->size())
1306                 return;
1307
1308         if (selection.start.par() == selection.end.par()) {
1309                 LyXCursor & startc = selection.start;
1310                 LyXCursor & endc = selection.end;
1311                 recordUndo(Undo::INSERT, this, startc.par());
1312                 getPar(startc)->rejectChange(startc.pos(), endc.pos());
1313                 finishUndo();
1314                 clearSelection();
1315                 redoParagraph(getPar(startc));
1316                 setCursorIntern(startc.par(), 0);
1317         }
1318 #warning handle multi par selection
1319 }
1320
1321
1322 // This function is only used by the spellchecker for NextWord().
1323 // It doesn't handle LYX_ACCENTs and probably never will.
1324 WordLangTuple const LyXText::selectNextWordToSpellcheck(float & value)
1325 {
1326         if (the_locking_inset) {
1327                 WordLangTuple word =
1328                         the_locking_inset->selectNextWordToSpellcheck(bv(), value);
1329                 if (!word.word().empty()) {
1330                         value += float(cursor.y());
1331                         value /= float(height);
1332                         return word;
1333                 }
1334                 // we have to go on checking so move cursor to the next char
1335                 if (cursor.pos() == cursorPar()->size()) {
1336                         if (cursor.par() + 1 == int(ownerParagraphs().size()))
1337                                 return word;
1338                         cursor.par(cursor.par() + 1);
1339                         cursor.pos(0);
1340                 } else {
1341                         cursor.pos(cursor.pos() + 1);
1342                 }
1343         }
1344         int const tmppar = cursor.par();
1345
1346         // If this is not the very first word, skip rest of
1347         // current word because we are probably in the middle
1348         // of a word if there is text here.
1349         if (cursor.pos() || cursor.par() != 0) {
1350                 while (cursor.pos() < cursorPar()->size()
1351                        && cursorPar()->isLetter(cursor.pos()))
1352                         cursor.pos(cursor.pos() + 1);
1353         }
1354
1355         // Now, skip until we have real text (will jump paragraphs)
1356         while (true) {
1357                 ParagraphList::iterator cpit = cursorPar();
1358                 pos_type const cpos = cursor.pos();
1359
1360                 if (cpos == cpit->size()) {
1361                         if (cursor.par() + 1 != int(ownerParagraphs().size())) {
1362                                 cursor.par(cursor.par() + 1);
1363                                 cursor.pos(0);
1364                                 continue;
1365                         }
1366                         break;
1367                 }
1368
1369                 bool const is_good_inset = cpit->isInset(cpos)
1370                         && cpit->getInset(cpos)->allowSpellcheck();
1371
1372                 if (!isDeletedText(*cpit, cpos)
1373                     && (is_good_inset || cpit->isLetter(cpos)))
1374                         break;
1375
1376                 cursor.pos(cpos + 1);
1377         }
1378
1379         // now check if we hit an inset so it has to be a inset containing text!
1380         if (cursor.pos() < cursorPar()->size() &&
1381             cursorPar()->isInset(cursor.pos())) {
1382                 // lock the inset!
1383                 FuncRequest cmd(bv(), LFUN_INSET_EDIT, "left");
1384                 cursorPar()->getInset(cursor.pos())->dispatch(cmd);
1385                 // now call us again to do the above trick
1386                 // but obviously we have to start from down below ;)
1387                 return bv()->text->selectNextWordToSpellcheck(value);
1388         }
1389
1390         // Update the value if we changed paragraphs
1391         if (cursor.par() != tmppar) {
1392                 setCursor(cursor.par(), cursor.pos());
1393                 value = float(cursor.y())/float(height);
1394         }
1395
1396         // Start the selection from here
1397         selection.cursor = cursor;
1398
1399         string lang_code = getFont(cursorPar(), cursor.pos()).language()->code();
1400         // and find the end of the word (insets like optional hyphens
1401         // and ligature break are part of a word)
1402         while (cursor.pos() < cursorPar()->size()
1403                && cursorPar()->isLetter(cursor.pos())
1404                && !isDeletedText(*cursorPar(), cursor.pos()))
1405                 cursor.pos(cursor.pos() + 1);
1406
1407         // Finally, we copy the word to a string and return it
1408         string str;
1409         if (selection.cursor.pos() < cursor.pos()) {
1410                 for (pos_type i = selection.cursor.pos(); i < cursor.pos(); ++i) {
1411                         if (!cursorPar()->isInset(i))
1412                                 str += cursorPar()->getChar(i);
1413                 }
1414         }
1415         return WordLangTuple(str, lang_code);
1416 }
1417
1418
1419 // This one is also only for the spellchecker
1420 void LyXText::selectSelectedWord()
1421 {
1422         if (the_locking_inset) {
1423                 the_locking_inset->selectSelectedWord(bv());
1424                 return;
1425         }
1426         // move cursor to the beginning
1427         setCursor(selection.cursor.par(), selection.cursor.pos());
1428
1429         // set the sel cursor
1430         selection.cursor = cursor;
1431
1432         // now find the end of the word
1433         while (cursor.pos() < cursorPar()->size()
1434                && cursorPar()->isLetter(cursor.pos()))
1435                 cursor.pos(cursor.pos() + 1);
1436
1437         setCursor(cursorPar(), cursor.pos());
1438
1439         // finally set the selection
1440         setSelection();
1441 }
1442
1443
1444 // Delete from cursor up to the end of the current or next word.
1445 void LyXText::deleteWordForward()
1446 {
1447         if (cursorPar()->empty())
1448                 cursorRight(bv());
1449         else {
1450                 LyXCursor tmpcursor = cursor;
1451                 selection.set(true); // to avoid deletion
1452                 cursorRightOneWord();
1453                 setCursor(tmpcursor, tmpcursor.par(), tmpcursor.pos());
1454                 selection.cursor = cursor;
1455                 cursor = tmpcursor;
1456                 setSelection();
1457                 cutSelection(true, false);
1458         }
1459 }
1460
1461
1462 // Delete from cursor to start of current or prior word.
1463 void LyXText::deleteWordBackward()
1464 {
1465         if (cursorPar()->empty())
1466                 cursorLeft(bv());
1467         else {
1468                 LyXCursor tmpcursor = cursor;
1469                 selection.set(true); // to avoid deletion
1470                 cursorLeftOneWord();
1471                 setCursor(tmpcursor, tmpcursor.par(), tmpcursor.pos());
1472                 selection.cursor = cursor;
1473                 cursor = tmpcursor;
1474                 setSelection();
1475                 cutSelection(true, false);
1476         }
1477 }
1478
1479
1480 // Kill to end of line.
1481 void LyXText::deleteLineForward()
1482 {
1483         if (cursorPar()->empty()) {
1484                 // Paragraph is empty, so we just go to the right
1485                 cursorRight(bv());
1486         } else {
1487                 LyXCursor tmpcursor = cursor;
1488                 // We can't store the row over a regular setCursor
1489                 // so we set it to 0 and reset it afterwards.
1490                 selection.set(true); // to avoid deletion
1491                 cursorEnd();
1492                 setCursor(tmpcursor, tmpcursor.par(), tmpcursor.pos());
1493                 selection.cursor = cursor;
1494                 cursor = tmpcursor;
1495                 setSelection();
1496                 // What is this test for ??? (JMarc)
1497                 if (!selection.set())
1498                         deleteWordForward();
1499                 else
1500                         cutSelection(true, false);
1501         }
1502 }
1503
1504
1505 void LyXText::changeCase(LyXText::TextCase action)
1506 {
1507         LyXCursor from;
1508         LyXCursor to;
1509
1510         if (selection.set()) {
1511                 from = selection.start;
1512                 to = selection.end;
1513         } else {
1514                 from = cursor;
1515                 ::getWord(*this, from, to, lyx::PARTIAL_WORD, ownerParagraphs());
1516                 setCursor(to.par(), to.pos() + 1);
1517         }
1518
1519         recordUndo(Undo::ATOMIC, this, from.par(), to.par());
1520
1521         pos_type pos = from.pos();
1522         int par = from.par();
1523
1524         while (par != int(ownerParagraphs().size()) &&
1525                (pos != to.pos() || par != to.par())) {
1526                 ParagraphList::iterator pit = getPar(par);
1527                 if (pos == pit->size()) {
1528                         ++par;
1529                         pos = 0;
1530                         continue;
1531                 }
1532                 unsigned char c = pit->getChar(pos);
1533                 if (c != Paragraph::META_INSET) {
1534                         switch (action) {
1535                         case text_lowercase:
1536                                 c = lowercase(c);
1537                                 break;
1538                         case text_capitalization:
1539                                 c = uppercase(c);
1540                                 action = text_lowercase;
1541                                 break;
1542                         case text_uppercase:
1543                                 c = uppercase(c);
1544                                 break;
1545                         }
1546                 }
1547 #warning changes
1548                 pit->setChar(pos, c);
1549                 ++pos;
1550         }
1551 }
1552
1553
1554 void LyXText::Delete()
1555 {
1556         // this is a very easy implementation
1557
1558         LyXCursor old_cursor = cursor;
1559         int const old_cur_par_id = cursorPar()->id();
1560         int const old_cur_par_prev_id =
1561                 old_cursor.par() ? getPar(old_cursor.par() - 1)->id() : -1;
1562
1563         // just move to the right
1564         cursorRight(bv());
1565
1566         // CHECK Look at the comment here.
1567         // This check is not very good...
1568         // The cursorRightIntern calls DeleteEmptyParagraphMechanism
1569         // and that can very well delete the par or par->previous in
1570         // old_cursor. Will a solution where we compare paragraph id's
1571         //work better?
1572         int iid = cursor.par() ? getPar(cursor.par() - 1)->id() : -1;
1573         if (iid == old_cur_par_prev_id && cursorPar()->id() != old_cur_par_id) {
1574                 // delete-empty-paragraph-mechanism has done it
1575                 return;
1576         }
1577
1578         // if you had success make a backspace
1579         if (old_cursor.par() != cursor.par() || old_cursor.pos() != cursor.pos()) {
1580                 recordUndo(Undo::DELETE, this, old_cursor.par());
1581                 backspace();
1582         }
1583 }
1584
1585
1586 void LyXText::backspace()
1587 {
1588         // Get the font that is used to calculate the baselineskip
1589         ParagraphList::iterator pit = cursorPar();
1590         pos_type lastpos = pit->size();
1591
1592         if (cursor.pos() == 0) {
1593                 // The cursor is at the beginning of a paragraph,
1594                 // so the the backspace will collapse two paragraphs into one.
1595
1596                 // but it's not allowed unless it's new
1597                 if (pit->isChangeEdited(0, pit->size()))
1598                         return;
1599
1600                 // we may paste some paragraphs
1601
1602                 // is it an empty paragraph?
1603
1604                 if (lastpos == 0 || (lastpos == 1 && pit->isSeparator(0))) {
1605                         // This is an empty paragraph and we delete it just
1606                         // by moving the cursor one step
1607                         // left and let the DeleteEmptyParagraphMechanism
1608                         // handle the actual deletion of the paragraph.
1609
1610                         if (cursor.par()) {
1611                                 ParagraphList::iterator tmppit = getPar(cursor.par() - 1);
1612                                 if (cursorPar()->layout() == tmppit->layout()
1613                                     && cursorPar()->getAlign() == tmppit->getAlign()) {
1614                                         // Inherit bottom DTD from the paragraph below.
1615                                         // (the one we are deleting)
1616                                         tmppit->params().spaceBottom(cursorPar()->params().spaceBottom());
1617                                 }
1618
1619                                 cursorLeft(bv());
1620
1621                                 // the layout things can change the height of a row !
1622                                 redoParagraph();
1623                                 return;
1624                         }
1625                 }
1626
1627                 if (cursor.par() != 0)
1628                         recordUndo(Undo::DELETE, this, cursor.par() - 1, cursor.par());
1629
1630                 ParagraphList::iterator tmppit = cursorPar();
1631                 // We used to do cursorLeftIntern() here, but it is
1632                 // not a good idea since it triggers the auto-delete
1633                 // mechanism. So we do a cursorLeftIntern()-lite,
1634                 // without the dreaded mechanism. (JMarc)
1635                 if (cursor.par() != 0) {
1636                         // steps into the above paragraph.
1637                         setCursorIntern(cursor.par() - 1,
1638                                         getPar(cursor.par() - 1)->size(),
1639                                         false);
1640                 }
1641
1642                 // Pasting is not allowed, if the paragraphs have different
1643                 // layout. I think it is a real bug of all other
1644                 // word processors to allow it. It confuses the user.
1645                 // Correction: Pasting is always allowed with standard-layout
1646                 Buffer & buf = *bv()->buffer();
1647                 BufferParams const & bufparams = buf.params();
1648                 LyXTextClass const & tclass = bufparams.getLyXTextClass();
1649
1650                 if (cursorPar() != tmppit
1651                     && (cursorPar()->layout() == tmppit->layout()
1652                         || tmppit->layout() == tclass.defaultLayout())
1653                     && cursorPar()->getAlign() == tmppit->getAlign()) {
1654                         mergeParagraph(bufparams,
1655                                        buf.paragraphs(), cursorPar());
1656
1657                         if (cursor.pos() && cursorPar()->isSeparator(cursor.pos() - 1))
1658                                 cursor.pos(cursor.pos() - 1);
1659
1660                         // the row may have changed, block, hfills etc.
1661                         updateCounters();
1662                         setCursor(cursor.par(), cursor.pos(), false);
1663                 }
1664         } else {
1665                 // this is the code for a normal backspace, not pasting
1666                 // any paragraphs
1667                 recordUndo(Undo::DELETE, this, cursor.par());
1668                 // We used to do cursorLeftIntern() here, but it is
1669                 // not a good idea since it triggers the auto-delete
1670                 // mechanism. So we do a cursorLeftIntern()-lite,
1671                 // without the dreaded mechanism. (JMarc)
1672                 setCursorIntern(cursor.par(), cursor.pos() - 1,
1673                                 false, cursor.boundary());
1674                 cursorPar()->erase(cursor.pos());
1675         }
1676
1677         lastpos = cursorPar()->size();
1678         if (cursor.pos() == lastpos)
1679                 setCurrentFont();
1680
1681         redoParagraph();
1682         setCursor(cursor.par(), cursor.pos(), false, !cursor.boundary());
1683 }
1684
1685
1686 ParagraphList::iterator LyXText::cursorPar() const
1687 {
1688         if (cursor.par() != cache_pos_) {
1689                 cache_pos_ = cursor.par();
1690                 cache_par_ = getPar(cache_pos_);
1691         }
1692         return cache_par_;
1693 }
1694
1695
1696 RowList::iterator LyXText::cursorRow() const
1697 {
1698         return cursorPar()->getRow(cursor.pos());
1699 }
1700
1701
1702 ParagraphList::iterator LyXText::getPar(LyXCursor const & cur) const
1703 {
1704         return getPar(cur.par());
1705 }
1706
1707
1708 ParagraphList::iterator LyXText::getPar(int par) const
1709 {
1710         BOOST_ASSERT(par >= 0);
1711         BOOST_ASSERT(par < int(ownerParagraphs().size()));
1712         ParagraphList::iterator pit = ownerParagraphs().begin();
1713         std::advance(pit, par);
1714         return pit;
1715 }
1716
1717
1718 RowList::iterator
1719 LyXText::getRowNearY(int y, ParagraphList::iterator & pit) const
1720 {
1721         //lyxerr << "getRowNearY: y " << y << endl;
1722
1723         pit = boost::prior(ownerParagraphs().end());
1724
1725         RowList::iterator rit = lastRow();
1726         RowList::iterator rbegin = firstRow();
1727
1728         while (rit != rbegin && int(pit->y + rit->y_offset()) > y)
1729                 previousRow(pit, rit);
1730
1731         return rit;
1732 }
1733
1734
1735 int LyXText::getDepth() const
1736 {
1737         return cursorPar()->getDepth();
1738 }
1739
1740
1741 RowList::iterator LyXText::firstRow() const
1742 {
1743         return ownerParagraphs().front().rows.begin();
1744 }
1745
1746
1747 RowList::iterator LyXText::lastRow() const
1748 {
1749         return boost::prior(endRow());
1750 }
1751
1752
1753 RowList::iterator LyXText::endRow() const
1754 {
1755         return ownerParagraphs().back().rows.end();
1756 }
1757
1758
1759 void LyXText::nextRow(ParagraphList::iterator & pit,
1760         RowList::iterator & rit) const
1761 {
1762         ++rit;
1763         if (rit == pit->rows.end()) {
1764                 ++pit;
1765                 if (pit == ownerParagraphs().end())
1766                         --pit;
1767                 else
1768                         rit = pit->rows.begin();
1769         }
1770 }
1771
1772
1773 void LyXText::previousRow(ParagraphList::iterator & pit,
1774         RowList::iterator & rit) const
1775 {
1776         if (rit != pit->rows.begin())
1777                 --rit;
1778         else {
1779                 BOOST_ASSERT(pit != ownerParagraphs().begin());
1780                 --pit;
1781                 rit = boost::prior(pit->rows.end());
1782         }
1783 }
1784
1785
1786 string LyXText::selectionAsString(Buffer const & buffer, bool label) const
1787 {
1788         if (!selection.set())
1789                 return string();
1790
1791         // should be const ...
1792         ParagraphList::iterator startpit = getPar(selection.start);
1793         ParagraphList::iterator endpit = getPar(selection.end);
1794         size_t const startpos = selection.start.pos();
1795         size_t const endpos = selection.end.pos();
1796
1797         if (startpit == endpit)
1798                 return startpit->asString(buffer, startpos, endpos, label);
1799
1800         // First paragraph in selection
1801         string result =
1802                 startpit->asString(buffer, startpos, startpit->size(), label) + "\n\n";
1803
1804         // The paragraphs in between (if any)
1805         ParagraphList::iterator pit = startpit;
1806         for (++pit; pit != endpit; ++pit)
1807                 result += pit->asString(buffer, 0, pit->size(), label) + "\n\n";
1808
1809         // Last paragraph in selection
1810         result += endpit->asString(buffer, 0, endpos, label);
1811
1812         return result;
1813 }
1814
1815
1816 int LyXText::parOffset(ParagraphList::iterator pit) const
1817 {
1818         return std::distance(ownerParagraphs().begin(), pit);
1819 }
1820
1821
1822 void LyXText::redoParagraphInternal(ParagraphList::iterator pit)
1823 {
1824         // remove rows of paragraph, keep track of height changes
1825         height -= pit->height;
1826
1827         // clear old data
1828         pit->rows.clear();
1829         pit->height = 0;
1830         pit->width = 0;
1831
1832         // redo insets
1833         InsetList::iterator ii = pit->insetlist.begin();
1834         InsetList::iterator iend = pit->insetlist.end();
1835         for (; ii != iend; ++ii) {
1836                 Dimension dim;
1837                 MetricsInfo mi(bv(), getFont(pit, ii->pos), workWidth());
1838                 ii->inset->metrics(mi, dim);
1839         }
1840
1841         // rebreak the paragraph
1842         int const ww = workWidth();
1843         pos_type z = 0;
1844         do {
1845                 Row row(z);
1846                 rowBreakPoint(pit, row);
1847                 z = row.endpos();
1848                 fill(pit, row, ww);
1849                 prepareToPrint(pit, row);
1850                 setHeightOfRow(pit, row);
1851                 row.y_offset(pit->height);
1852                 pit->rows.push_back(row);
1853                 pit->width = std::max(pit->width, row.width());
1854                 pit->height += row.height();
1855         } while (z < pit->size());
1856
1857         height += pit->height;
1858         //lyxerr << "redoParagraph: " << pit->rows.size() << " rows\n";
1859 }
1860
1861
1862 void LyXText::redoParagraphs(ParagraphList::iterator pit,
1863   ParagraphList::iterator end)
1864 {
1865         for ( ; pit != end; ++pit)
1866                 redoParagraphInternal(pit);
1867         updateRowPositions();
1868 }
1869
1870
1871 void LyXText::redoParagraph(ParagraphList::iterator pit)
1872 {
1873         redoParagraphInternal(pit);
1874         updateRowPositions();
1875 }
1876
1877
1878 void LyXText::fullRebreak()
1879 {
1880         redoParagraphs(ownerParagraphs().begin(), ownerParagraphs().end());
1881         redoCursor();
1882         selection.cursor = cursor;
1883 }
1884
1885
1886 void LyXText::metrics(MetricsInfo & mi, Dimension & dim)
1887 {
1888         //lyxerr << "LyXText::metrics: width: " << mi.base.textwidth
1889         //      << " workWidth: " << workWidth() << "\nfont: " << mi.base.font << endl;
1890         //BOOST_ASSERT(mi.base.textwidth);
1891         //anchor_y_ = 0;
1892
1893         // rebuild row cache. This recomputes height as well.
1894         redoParagraphs(ownerParagraphs().begin(), ownerParagraphs().end());
1895
1896         width = maxParagraphWidth(ownerParagraphs());
1897
1898         // final dimension
1899         dim.asc = firstRow()->ascent_of_text();
1900         dim.des = height - dim.asc;
1901         dim.wid = std::max(mi.base.textwidth, int(width));
1902 }
1903
1904
1905 bool LyXText::isLastRow(ParagraphList::iterator pit, Row const & row) const
1906 {
1907         return row.endpos() >= pit->size()
1908                && boost::next(pit) == ownerParagraphs().end();
1909 }
1910
1911
1912 bool LyXText::isFirstRow(ParagraphList::iterator pit, Row const & row) const
1913 {
1914         return row.pos() == 0 && pit == ownerParagraphs().begin();
1915 }