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