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