]> git.lyx.org Git - lyx.git/blob - src/text2.C
remove broken operator==() for Paragraphs
[lyx.git] / src / text2.C
1 /* This file is part of
2  * ======================================================
3  *
4  *           LyX, The Document Processor
5  *
6  *           Copyright 1995 Matthias Ettrich
7  *           Copyright 1995-2001 The LyX Team.
8  *
9  * ====================================================== */
10
11 #include <config.h>
12
13 #include "lyxtext.h"
14 #include "LString.h"
15 #include "Lsstream.h"
16 #include "paragraph.h"
17 #include "funcrequest.h"
18 #include "frontends/LyXView.h"
19 #include "undo_funcs.h"
20 #include "buffer.h"
21 #include "buffer_funcs.h"
22 #include "bufferparams.h"
23 #include "errorlist.h"
24 #include "gettext.h"
25 #include "BufferView.h"
26 #include "CutAndPaste.h"
27 #include "frontends/Painter.h"
28 #include "frontends/font_metrics.h"
29 #include "debug.h"
30 #include "lyxrc.h"
31 #include "lyxrow.h"
32 #include "FloatList.h"
33 #include "language.h"
34 #include "ParagraphParameters.h"
35 #include "counters.h"
36 #include "lyxrow_funcs.h"
37 #include "metricsinfo.h"
38 #include "paragraph_funcs.h"
39
40 #include "insets/insetbibitem.h"
41 #include "insets/insetenv.h"
42 #include "insets/insetfloat.h"
43 #include "insets/insetwrap.h"
44
45 #include "support/LAssert.h"
46 #include "support/textutils.h"
47 #include "support/lstrings.h"
48
49 #include <boost/tuple/tuple.hpp>
50
51 #include <algorithm>
52
53 using namespace lyx::support;
54
55 using std::vector;
56 using std::copy;
57 using std::endl;
58 using std::find;
59 using std::pair;
60 using lyx::pos_type;
61
62
63 LyXText::LyXText(BufferView * bv)
64         : height(0), width(0), anchor_row_offset_(0),
65           inset_owner(0), the_locking_inset(0), bv_owner(bv)
66 {
67         anchor_row_ = rows().end();
68         need_refresh_ = true;
69 }
70
71
72 LyXText::LyXText(BufferView * bv, InsetText * inset)
73         : height(0), width(0), anchor_row_offset_(0),
74           inset_owner(inset), the_locking_inset(0), bv_owner(bv)
75 {
76         anchor_row_ = rows().end();
77         need_refresh_ = true;
78 }
79
80
81 void LyXText::init(BufferView * bview)
82 {
83         bv_owner = bview;
84
85         rowlist_.clear();
86         width = height = 0;
87         need_refresh_ = true;
88
89         anchor_row_ = rows().end();
90         anchor_row_offset_ = 0;
91
92         ParagraphList::iterator pit = ownerParagraphs().begin();
93         ParagraphList::iterator end = ownerParagraphs().end();
94
95         current_font = getFont(pit, 0);
96
97         for (; pit != end; ++pit)
98                 insertParagraph(pit, rowlist_.end());
99
100         setCursorIntern(rowlist_.begin()->par(), 0);
101         selection.cursor = cursor;
102
103         updateCounters();
104 }
105
106
107 // Gets the fully instantiated font at a given position in a paragraph
108 // Basically the same routine as Paragraph::getFont() in paragraph.C.
109 // The difference is that this one is used for displaying, and thus we
110 // are allowed to make cosmetic improvements. For instance make footnotes
111 // smaller. (Asger)
112 // If position is -1, we get the layout font of the paragraph.
113 // If position is -2, we get the font of the manual label of the paragraph.
114 LyXFont LyXText::getFont(ParagraphList::iterator pit, pos_type pos) const
115 {
116         Assert(pos >= 0);
117
118         LyXLayout_ptr const & layout = pit->layout();
119 #warning broken?
120         BufferParams const & params = bv()->buffer()->params;
121
122         // We specialize the 95% common case:
123         if (!pit->getDepth()) {
124                 if (layout->labeltype == LABEL_MANUAL
125                     && pos < pit->beginningOfBody()) {
126                         // 1% goes here
127                         LyXFont f = pit->getFontSettings(params, pos);
128                         if (pit->inInset())
129                                 pit->inInset()->getDrawFont(f);
130                         return f.realize(layout->reslabelfont);
131                 } else {
132                         LyXFont f = pit->getFontSettings(params, pos);
133                         if (pit->inInset())
134                                 pit->inInset()->getDrawFont(f);
135                         return f.realize(layout->resfont);
136                 }
137         }
138
139         // The uncommon case need not be optimized as much
140
141         LyXFont layoutfont;
142
143         if (pos < pit->beginningOfBody()) {
144                 // 1% goes here
145                 layoutfont = layout->labelfont;
146         } else {
147                 // 99% goes here
148                 layoutfont = layout->font;
149         }
150
151         LyXFont tmpfont = pit->getFontSettings(params, pos);
152         tmpfont.realize(layoutfont);
153
154         if (pit->inInset())
155                 pit->inInset()->getDrawFont(tmpfont);
156
157         // Realize with the fonts of lesser depth.
158         tmpfont.realize(outerFont(pit, ownerParagraphs()));
159         tmpfont.realize(defaultfont_);
160
161         return tmpfont;
162 }
163
164
165 LyXFont LyXText::getLayoutFont(ParagraphList::iterator pit) const
166 {
167         LyXLayout_ptr const & layout = pit->layout();
168
169         if (!pit->getDepth())
170                 return layout->resfont;
171
172         LyXFont font = layout->font;
173         // Realize with the fonts of lesser depth.
174         font.realize(outerFont(pit, ownerParagraphs()));
175         font.realize(defaultfont_);
176
177         return font;
178 }
179
180
181 LyXFont LyXText::getLabelFont(ParagraphList::iterator pit) const
182 {
183         LyXLayout_ptr const & layout = pit->layout();
184
185         if (!pit->getDepth())
186                 return layout->reslabelfont;
187
188         LyXFont font = layout->labelfont;
189         // Realize with the fonts of lesser depth.
190         font.realize(outerFont(pit, ownerParagraphs()));
191         font.realize(defaultfont_);
192
193         return font;
194 }
195
196
197 void LyXText::setCharFont(ParagraphList::iterator pit,
198                           pos_type pos, LyXFont const & fnt,
199                           bool toggleall)
200 {
201         BufferParams const & params = bv()->buffer()->params;
202         LyXFont font = getFont(pit, pos);
203         font.update(fnt, params.language, toggleall);
204         // Let the insets convert their font
205         if (pit->isInset(pos)) {
206                 InsetOld * inset = pit->getInset(pos);
207                 if (isEditableInset(inset)) {
208                         static_cast<UpdatableInset *>(inset)
209                                 ->setFont(bv(), fnt, toggleall, true);
210                 }
211         }
212
213         // Plug through to version below:
214         setCharFont(pit, pos, font);
215 }
216
217
218 void LyXText::setCharFont(
219         ParagraphList::iterator pit, pos_type pos, LyXFont const & fnt)
220 {
221         LyXFont font = fnt;
222         LyXLayout_ptr const & layout = pit->layout();
223
224         // Get concrete layout font to reduce against
225         LyXFont layoutfont;
226
227         if (pos < pit->beginningOfBody())
228                 layoutfont = layout->labelfont;
229         else
230                 layoutfont = layout->font;
231
232         // Realize against environment font information
233         if (pit->getDepth()) {
234                 ParagraphList::iterator tp = pit;
235                 while (!layoutfont.resolved() &&
236                        tp != ownerParagraphs().end() &&
237                        tp->getDepth()) {
238                         tp = outerHook(tp, ownerParagraphs());
239                         if (tp != ownerParagraphs().end())
240                                 layoutfont.realize(tp->layout()->font);
241                 }
242         }
243
244         layoutfont.realize(defaultfont_);
245
246         // Now, reduce font against full layout font
247         font.reduce(layoutfont);
248
249         pit->setFont(pos, font);
250 }
251
252
253 // removes the row and reset the touched counters
254 void LyXText::removeRow(RowList::iterator rit)
255 {
256         if (anchor_row_ == rit) {
257                 if (rit != rows().begin()) {
258                         anchor_row_ = boost::prior(rit);
259                         anchor_row_offset_ += anchor_row_->height();
260                 } else {
261                         anchor_row_ = boost::next(rit);
262                         anchor_row_offset_ -= rit->height();
263                 }
264         }
265
266         // the text becomes smaller
267         height -= rit->height();
268
269         rowlist_.erase(rit);
270 }
271
272
273 // remove all following rows of the paragraph of the specified row.
274 void LyXText::removeParagraph(RowList::iterator rit)
275 {
276         ParagraphList::iterator tmppit = rit->par();
277         ++rit;
278
279         while (rit != rows().end() && rit->par() == tmppit) {
280                 RowList::iterator tmprit = boost::next(rit);
281                 removeRow(rit);
282                 rit = tmprit;
283         }
284 }
285
286
287 void LyXText::insertParagraph(ParagraphList::iterator pit,
288                               RowList::iterator rowit)
289 {
290         // insert a new row, starting at position 0
291         Row newrow(pit, 0);
292         RowList::iterator rit = rowlist_.insert(rowit, newrow);
293
294         // and now append the whole paragraph before the new row
295         appendParagraph(rit);
296 }
297
298
299 InsetOld * LyXText::getInset() const
300 {
301         ParagraphList::iterator pit = cursor.par();
302         pos_type const pos = cursor.pos();
303
304         if (pos < pit->size() && pit->isInset(pos)) {
305                 return pit->getInset(pos);
306         }
307         return 0;
308 }
309
310
311 void LyXText::toggleInset()
312 {
313         InsetOld * inset = getInset();
314         // is there an editable inset at cursor position?
315         if (!isEditableInset(inset)) {
316                 // No, try to see if we are inside a collapsable inset
317                 if (inset_owner && inset_owner->owner()
318                     && inset_owner->owner()->isOpen()) {
319                         bv()->unlockInset(inset_owner->owner());
320                         inset_owner->owner()->close(bv());
321                         bv()->getLyXText()->cursorRight(bv());
322                 }
323                 return;
324         }
325         //bv()->owner()->message(inset->editMessage());
326
327         // do we want to keep this?? (JMarc)
328         if (!isHighlyEditableInset(inset))
329                 recordUndo(bv(), Undo::ATOMIC);
330
331         if (inset->isOpen()) {
332                 inset->close(bv());
333         } else {
334                 inset->open(bv());
335         }
336
337         bv()->updateInset(inset);
338 }
339
340
341 /* used in setlayout */
342 // Asger is not sure we want to do this...
343 void LyXText::makeFontEntriesLayoutSpecific(BufferParams const & params,
344                                             Paragraph & par)
345 {
346         LyXLayout_ptr const & layout = par.layout();
347         pos_type const psize = par.size();
348
349         LyXFont layoutfont;
350         for (pos_type pos = 0; pos < psize; ++pos) {
351                 if (pos < par.beginningOfBody())
352                         layoutfont = layout->labelfont;
353                 else
354                         layoutfont = layout->font;
355
356                 LyXFont tmpfont = par.getFontSettings(params, pos);
357                 tmpfont.reduce(layoutfont);
358                 par.setFont(pos, tmpfont);
359         }
360 }
361
362
363 ParagraphList::iterator
364 LyXText::setLayout(LyXCursor & cur, LyXCursor & sstart_cur,
365                    LyXCursor & send_cur,
366                    string const & layout)
367 {
368         ParagraphList::iterator endpit = boost::next(send_cur.par());
369         ParagraphList::iterator undoendpit = endpit;
370         ParagraphList::iterator pars_end = ownerParagraphs().end();
371
372         if (endpit != pars_end && endpit->getDepth()) {
373                 while (endpit != pars_end && endpit->getDepth()) {
374                         ++endpit;
375                         undoendpit = endpit;
376                 }
377         } else if (endpit != pars_end) {
378                 // because of parindents etc.
379                 ++endpit;
380         }
381
382         recordUndo(bv(), Undo::ATOMIC, sstart_cur.par(), boost::prior(undoendpit));
383
384         // ok we have a selection. This is always between sstart_cur
385         // and sel_end cursor
386         cur = sstart_cur;
387         ParagraphList::iterator pit = sstart_cur.par();
388         ParagraphList::iterator epit = boost::next(send_cur.par());
389
390         LyXLayout_ptr const & lyxlayout =
391                 bv()->buffer()->params.getLyXTextClass()[layout];
392
393         do {
394                 pit->applyLayout(lyxlayout);
395                 makeFontEntriesLayoutSpecific(bv()->buffer()->params, *pit);
396                 ParagraphList::iterator fppit = pit;
397                 fppit->params().spaceTop(lyxlayout->fill_top ?
398                                          VSpace(VSpace::VFILL)
399                                          : VSpace(VSpace::NONE));
400                 fppit->params().spaceBottom(lyxlayout->fill_bottom ?
401                                             VSpace(VSpace::VFILL)
402                                             : VSpace(VSpace::NONE));
403                 if (lyxlayout->margintype == MARGIN_MANUAL)
404                         pit->setLabelWidthString(lyxlayout->labelstring());
405                 cur.par(pit);
406                 ++pit;
407         } while (pit != epit);
408
409         return endpit;
410 }
411
412
413 // set layout over selection and make a total rebreak of those paragraphs
414 void LyXText::setLayout(string const & layout)
415 {
416         LyXCursor tmpcursor = cursor;  // store the current cursor
417
418         // if there is no selection just set the layout
419         // of the current paragraph
420         if (!selection.set()) {
421                 selection.start = cursor;  // dummy selection
422                 selection.end = cursor;
423         }
424
425         // special handling of new environment insets
426         BufferParams const & params = bv()->buffer()->params;
427         LyXLayout_ptr const & lyxlayout = params.getLyXTextClass()[layout];
428         if (lyxlayout->is_environment) {
429                 // move everything in a new environment inset
430                 lyxerr << "setting layout " << layout << endl;
431                 bv()->owner()->dispatch(FuncRequest(LFUN_HOME));
432                 bv()->owner()->dispatch(FuncRequest(LFUN_ENDSEL));
433                 bv()->owner()->dispatch(FuncRequest(LFUN_CUT));
434                 InsetOld * inset = new InsetEnvironment(params, layout);
435                 if (bv()->insertInset(inset)) {
436                         //inset->edit(bv());
437                         //bv()->owner()->dispatch(FuncRequest(LFUN_PASTE));
438                 }
439                 else
440                         delete inset;
441                 return;
442         }
443
444         ParagraphList::iterator endpit = setLayout(cursor, selection.start,
445                                                    selection.end, layout);
446         redoParagraphs(selection.start, endpit);
447
448         // we have to reset the selection, because the
449         // geometry could have changed
450         setCursor(selection.start.par(), selection.start.pos(), false);
451         selection.cursor = cursor;
452         setCursor(selection.end.par(), selection.end.pos(), false);
453         updateCounters();
454         clearSelection();
455         setSelection();
456         setCursor(tmpcursor.par(), tmpcursor.pos(), true);
457 }
458
459
460 bool LyXText::changeDepth(bv_funcs::DEPTH_CHANGE type, bool test_only)
461 {
462         ParagraphList::iterator pit(cursor.par());
463         ParagraphList::iterator end(cursor.par());
464         ParagraphList::iterator start = pit;
465
466         if (selection.set()) {
467                 pit = selection.start.par();
468                 end = selection.end.par();
469                 start = pit;
470         }
471
472         ParagraphList::iterator pastend = boost::next(end);
473
474         if (!test_only)
475                 recordUndo(bv(), Undo::ATOMIC, start, end);
476
477         bool changed = false;
478
479         int prev_after_depth = 0;
480 #warning parlist ... could be nicer ?
481         if (start != ownerParagraphs().begin()) {
482                 prev_after_depth = boost::prior(start)->getMaxDepthAfter();
483         }
484
485         while (true) {
486                 int const depth = pit->params().depth();
487                 if (type == bv_funcs::INC_DEPTH) {
488                         if (depth < prev_after_depth
489                             && pit->layout()->labeltype != LABEL_BIBLIO) {
490                                 changed = true;
491                                 if (!test_only) {
492                                         pit->params().depth(depth + 1);
493                                 }
494
495                         }
496                 } else if (depth) {
497                         changed = true;
498                         if (!test_only)
499                                 pit->params().depth(depth - 1);
500                 }
501
502                 prev_after_depth = pit->getMaxDepthAfter();
503
504                 if (pit == end) {
505                         break;
506                 }
507
508                 ++pit;
509         }
510
511         if (test_only)
512                 return changed;
513
514         // Wow, redoParagraphs is stupid.
515         LyXCursor tmpcursor;
516         setCursor(tmpcursor, start, 0);
517
518         redoParagraphs(tmpcursor, pastend);
519
520         // We need to actually move the text->cursor. I don't
521         // understand why ...
522         tmpcursor = cursor;
523
524         // we have to reset the visual selection because the
525         // geometry could have changed
526         if (selection.set()) {
527                 setCursor(selection.start.par(), selection.start.pos());
528                 selection.cursor = cursor;
529                 setCursor(selection.end.par(), selection.end.pos());
530         }
531
532         // this handles the counter labels, and also fixes up
533         // depth values for follow-on (child) paragraphs
534         updateCounters();
535
536         setSelection();
537         setCursor(tmpcursor.par(), tmpcursor.pos());
538
539         return changed;
540 }
541
542
543 // set font over selection and make a total rebreak of those paragraphs
544 void LyXText::setFont(LyXFont const & font, bool toggleall)
545 {
546         // if there is no selection just set the current_font
547         if (!selection.set()) {
548                 // Determine basis font
549                 LyXFont layoutfont;
550                 if (cursor.pos() < cursor.par()->beginningOfBody()) {
551                         layoutfont = getLabelFont(cursor.par());
552                 } else {
553                         layoutfont = getLayoutFont(cursor.par());
554                 }
555                 // Update current font
556                 real_current_font.update(font,
557                                          bv()->buffer()->params.language,
558                                          toggleall);
559
560                 // Reduce to implicit settings
561                 current_font = real_current_font;
562                 current_font.reduce(layoutfont);
563                 // And resolve it completely
564                 real_current_font.realize(layoutfont);
565
566                 return;
567         }
568
569         LyXCursor tmpcursor = cursor; // store the current cursor
570
571         // ok we have a selection. This is always between sel_start_cursor
572         // and sel_end cursor
573
574         recordUndo(bv(), Undo::ATOMIC, selection.start.par(), selection.end.par());
575         freezeUndo();
576         cursor = selection.start;
577         while (cursor.par() != selection.end.par() ||
578                cursor.pos() < selection.end.pos())
579         {
580                 if (cursor.pos() < cursor.par()->size()) {
581                         // an open footnote should behave like a closed one
582                         setCharFont(cursor.par(), cursor.pos(),
583                                     font, toggleall);
584                         cursor.pos(cursor.pos() + 1);
585                 } else {
586                         cursor.pos(0);
587                         cursor.par(boost::next(cursor.par()));
588                 }
589         }
590         unFreezeUndo();
591
592         redoParagraphs(selection.start, boost::next(selection.end.par()));
593
594         // we have to reset the selection, because the
595         // geometry could have changed, but we keep
596         // it for user convenience
597         setCursor(selection.start.par(), selection.start.pos());
598         selection.cursor = cursor;
599         setCursor(selection.end.par(), selection.end.pos());
600         setSelection();
601         setCursor(tmpcursor.par(), tmpcursor.pos(), true,
602                   tmpcursor.boundary());
603 }
604
605
606 void LyXText::redoHeightOfParagraph()
607 {
608         RowList::iterator tmprow = cursorRow();
609
610         setHeightOfRow(tmprow);
611
612         while (tmprow != rows().begin()
613                && boost::prior(tmprow)->par() == tmprow->par()) {
614                 --tmprow;
615                 setHeightOfRow(tmprow);
616         }
617
618         postPaint();
619
620         setCursor(cursor.par(), cursor.pos(), false, cursor.boundary());
621 }
622
623
624 // deletes and inserts again all paragraphs between the cursor
625 // and the specified par
626 // This function is needed after SetLayout and SetFont etc.
627 void LyXText::redoParagraphs(LyXCursor const & cur,
628                              ParagraphList::iterator endpit)
629 {
630         RowList::iterator tmprit = getRow(cur);
631
632         ParagraphList::iterator first_phys_pit;
633         RowList::iterator prevrit;
634         if (tmprit == rows().begin()) {
635                 // A trick/hack for UNDO.
636                 // This is needed because in an UNDO/REDO we could have
637                 // changed the ownerParagraph() so the paragraph inside
638                 // the row is NOT my really first par anymore.
639                 // Got it Lars ;) (Jug 20011206)
640                 first_phys_pit = ownerParagraphs().begin();
641                 prevrit = rows().end();
642         } else {
643                 first_phys_pit = tmprit->par();
644                 while (tmprit != rows().begin()
645                        && boost::prior(tmprit)->par() == first_phys_pit)
646                 {
647                         --tmprit;
648                 }
649                 prevrit = boost::prior(tmprit);
650         }
651
652         // remove it
653         while (tmprit != rows().end() && tmprit->par() != endpit) {
654                 RowList::iterator tmprit2 = tmprit++;
655                 removeRow(tmprit2);
656         }
657
658         // Reinsert the paragraphs.
659         ParagraphList::iterator tmppit = first_phys_pit;
660
661         while (tmppit != ownerParagraphs().end()) {
662                 insertParagraph(tmppit, tmprit);
663                 while (tmprit != rows().end()
664                        && tmprit->par() == tmppit) {
665                         ++tmprit;
666                 }
667                 ++tmppit;
668                 if (tmppit == endpit)
669                         break;
670         }
671         if (prevrit != rows().end())
672                 setHeightOfRow(prevrit);
673         else
674                 setHeightOfRow(rows().begin());
675         postPaint();
676         if (tmprit != rows().end())
677                 setHeightOfRow(tmprit);
678
679         updateCounters();
680 }
681
682
683 void LyXText::fullRebreak()
684 {
685         init(bv());
686         setCursorIntern(cursor.par(), cursor.pos());
687 }
688
689
690 void LyXText::metrics(MetricsInfo & mi, Dimension & dim)
691 {
692         //lyxerr << "LyXText::metrics: width: " << mi.base.textwidth << "\n";
693
694         // rebuild row cache
695         rowlist_.clear();
696         width = height = 0;
697
698         anchor_row_ = rows().end();
699         anchor_row_offset_ = 0;
700
701         ParagraphList::iterator pit = ownerParagraphs().begin();
702         ParagraphList::iterator end = ownerParagraphs().end();
703
704         for (; pit != end; ++pit) {
705                 InsetList::iterator ii = pit->insetlist.begin();
706                 InsetList::iterator iend = pit->insetlist.end();
707                 for (; ii != iend; ++ii) {
708                         Dimension dim;
709                         MetricsInfo m = mi;
710                         ii->inset->metrics(m, dim);
711                 }
712
713                 // insert a new row, starting at position 0
714                 Row newrow(pit, 0);
715                 RowList::iterator rit = rowlist_.insert(rowlist_.end(), newrow);
716
717                 // and now append the whole paragraph before the new row
718                 appendParagraph(rit);
719         }
720
721         // compute height
722         //lyxerr << "height 0: " << height << "\n";
723         //for (RowList::iterator rit = rows().begin(); rit != rows().end(); ++rit) {
724         //      height += rit->height();
725         //}
726         //lyxerr << "height 1: " << height << "\n";
727
728         // final dimension
729         dim.asc = rows().begin()->ascent_of_text();
730         dim.des = height - dim.asc;
731         dim.wid = std::max(mi.base.textwidth, int(width));
732 }
733
734
735 void LyXText::partialRebreak()
736 {
737         if (rows().empty()) {
738                 init(bv());
739                 return;
740         }
741         breakAgain(rows().begin());
742 }
743
744
745 // important for the screen
746
747
748 // the cursor set functions have a special mechanism. When they
749 // realize, that you left an empty paragraph, they will delete it.
750 // They also delete the corresponding row
751
752 // need the selection cursor:
753 void LyXText::setSelection()
754 {
755         bool const lsel = TextCursor::setSelection();
756
757         if (inset_owner && (selection.set() || lsel))
758                 inset_owner->setUpdateStatus(InsetText::SELECTION);
759 }
760
761
762
763 void LyXText::clearSelection()
764 {
765         TextCursor::clearSelection();
766
767         // reset this in the bv_owner!
768         if (bv_owner && bv_owner->text)
769                 bv_owner->text->xsel_cache.set(false);
770 }
771
772
773 void LyXText::cursorHome()
774 {
775         setCursor(cursor.par(), cursorRow()->pos());
776 }
777
778
779 void LyXText::cursorEnd()
780 {
781         if (cursor.par()->empty())
782                 return;
783
784         RowList::iterator rit = cursorRow();
785         RowList::iterator next_rit = boost::next(rit);
786         ParagraphList::iterator pit = rit->par();
787         pos_type last_pos = lastPos(*this, rit);
788
789         if (next_rit == rows().end() || next_rit->par() != pit) {
790                 ++last_pos;
791         } else {
792                 if (pit->empty() ||
793                     (pit->getChar(last_pos) != ' ' && !pit->isNewline(last_pos))) {
794                         ++last_pos;
795                 }
796         }
797
798         setCursor(pit, last_pos);
799 }
800
801
802 void LyXText::cursorTop()
803 {
804         setCursor(ownerParagraphs().begin(), 0);
805 }
806
807
808 void LyXText::cursorBottom()
809 {
810         ParagraphList::iterator lastpit =
811                 boost::prior(ownerParagraphs().end());
812         setCursor(lastpit, lastpit->size());
813 }
814
815
816 void LyXText::toggleFree(LyXFont const & font, bool toggleall)
817 {
818         // If the mask is completely neutral, tell user
819         if (font == LyXFont(LyXFont::ALL_IGNORE)) {
820                 // Could only happen with user style
821                 bv()->owner()->message(_("No font change defined. Use Character under the Layout menu to define font change."));
822                 return;
823         }
824
825         // Try implicit word selection
826         // If there is a change in the language the implicit word selection
827         // is disabled.
828         LyXCursor resetCursor = cursor;
829         bool implicitSelection = (font.language() == ignore_language
830                                   && font.number() == LyXFont::IGNORE)
831                 ? selectWordWhenUnderCursor(lyx::WHOLE_WORD_STRICT) : false;
832
833         // Set font
834         setFont(font, toggleall);
835
836         // Implicit selections are cleared afterwards
837         //and cursor is set to the original position.
838         if (implicitSelection) {
839                 clearSelection();
840                 cursor = resetCursor;
841                 setCursor(cursor.par(), cursor.pos());
842                 selection.cursor = cursor;
843         }
844         if (inset_owner)
845                 inset_owner->setUpdateStatus(InsetText::CURSOR_PAR);
846 }
847
848
849 string LyXText::getStringToIndex()
850 {
851         // Try implicit word selection
852         // If there is a change in the language the implicit word selection
853         // is disabled.
854         LyXCursor const reset_cursor = cursor;
855         bool const implicitSelection =
856                 selectWordWhenUnderCursor(lyx::PREVIOUS_WORD);
857
858         string idxstring;
859         if (!selection.set())
860                 bv()->owner()->message(_("Nothing to index!"));
861         else if (selection.start.par() != selection.end.par())
862                 bv()->owner()->message(_("Cannot index more than one paragraph!"));
863         else
864                 idxstring = selectionAsString(bv()->buffer(), false);
865
866         // Reset cursors to their original position.
867         cursor = reset_cursor;
868         setCursor(cursor.par(), cursor.pos());
869         selection.cursor = cursor;
870
871         // Clear the implicit selection.
872         if (implicitSelection)
873                 clearSelection();
874
875         return idxstring;
876 }
877
878
879 // the DTP switches for paragraphs. LyX will store them in the first
880 // physicla paragraph. When a paragraph is broken, the top settings rest,
881 // the bottom settings are given to the new one. So I can make shure,
882 // they do not duplicate themself and you cannnot make dirty things with
883 // them!
884
885 void LyXText::setParagraph(bool line_top, bool line_bottom,
886                            bool pagebreak_top, bool pagebreak_bottom,
887                            VSpace const & space_top,
888                            VSpace const & space_bottom,
889                            Spacing const & spacing,
890                            LyXAlignment align,
891                            string const & labelwidthstring,
892                            bool noindent)
893 {
894         LyXCursor tmpcursor = cursor;
895         if (!selection.set()) {
896                 selection.start = cursor;
897                 selection.end = cursor;
898         }
899
900         // make sure that the depth behind the selection are restored, too
901         ParagraphList::iterator endpit = boost::next(selection.end.par());
902         ParagraphList::iterator undoendpit = endpit;
903         ParagraphList::iterator pars_end = ownerParagraphs().end();
904
905         if (endpit != pars_end && endpit->getDepth()) {
906                 while (endpit != pars_end && endpit->getDepth()) {
907                         ++endpit;
908                         undoendpit = endpit;
909                 }
910         } else if (endpit != pars_end) {
911                 // because of parindents etc.
912                 ++endpit;
913         }
914
915         recordUndo(bv(), Undo::ATOMIC, selection.start.par(),
916                 boost::prior(undoendpit));
917
918
919         ParagraphList::iterator tmppit = selection.end.par();
920
921         while (tmppit != boost::prior(selection.start.par())) {
922                 setCursor(tmppit, 0);
923
924                 ParagraphList::iterator pit = cursor.par();
925                 ParagraphParameters & params = pit->params();
926
927                 params.lineTop(line_top);
928                 params.lineBottom(line_bottom);
929                 params.pagebreakTop(pagebreak_top);
930                 params.pagebreakBottom(pagebreak_bottom);
931                 params.spaceTop(space_top);
932                 params.spaceBottom(space_bottom);
933                 params.spacing(spacing);
934                 // does the layout allow the new alignment?
935                 LyXLayout_ptr const & layout = pit->layout();
936
937                 if (align == LYX_ALIGN_LAYOUT)
938                         align = layout->align;
939                 if (align & layout->alignpossible) {
940                         if (align == layout->align)
941                                 params.align(LYX_ALIGN_LAYOUT);
942                         else
943                                 params.align(align);
944                 }
945                 pit->setLabelWidthString(labelwidthstring);
946                 params.noindent(noindent);
947                 tmppit = boost::prior(pit);
948         }
949         postPaint();
950
951         redoParagraphs(selection.start, endpit);
952
953         clearSelection();
954         setCursor(selection.start.par(), selection.start.pos());
955         selection.cursor = cursor;
956         setCursor(selection.end.par(), selection.end.pos());
957         setSelection();
958         setCursor(tmpcursor.par(), tmpcursor.pos());
959         if (inset_owner)
960                 bv()->updateInset(inset_owner);
961 }
962
963
964 // set the counter of a paragraph. This includes the labels
965 void LyXText::setCounter(Buffer const * buf, ParagraphList::iterator pit)
966 {
967         LyXTextClass const & textclass = buf->params.getLyXTextClass();
968         LyXLayout_ptr const & layout = pit->layout();
969
970         if (pit != ownerParagraphs().begin()) {
971
972                 pit->params().appendix(boost::prior(pit)->params().appendix());
973                 if (!pit->params().appendix() &&
974                     pit->params().startOfAppendix()) {
975                         pit->params().appendix(true);
976                         textclass.counters().reset();
977                 }
978                 pit->enumdepth = boost::prior(pit)->enumdepth;
979                 pit->itemdepth = boost::prior(pit)->itemdepth;
980         } else {
981                 pit->params().appendix(pit->params().startOfAppendix());
982                 pit->enumdepth = 0;
983                 pit->itemdepth = 0;
984         }
985
986         /* Maybe we have to increment the enumeration depth.
987          * BUT, enumeration in a footnote is considered in isolation from its
988          *      surrounding paragraph so don't increment if this is the
989          *      first line of the footnote
990          * AND, bibliographies can't have their depth changed ie. they
991          *      are always of depth 0
992          */
993         if (pit != ownerParagraphs().begin()
994             && boost::prior(pit)->getDepth() < pit->getDepth()
995             && boost::prior(pit)->layout()->labeltype == LABEL_COUNTER_ENUMI
996             && pit->enumdepth < 3
997             && layout->labeltype != LABEL_BIBLIO) {
998                 pit->enumdepth++;
999         }
1000
1001         // Maybe we have to decrement the enumeration depth, see note above
1002         if (pit != ownerParagraphs().begin()
1003             && boost::prior(pit)->getDepth() > pit->getDepth()
1004             && layout->labeltype != LABEL_BIBLIO) {
1005                 pit->enumdepth = depthHook(pit, ownerParagraphs(),
1006                                            pit->getDepth())->enumdepth;
1007         }
1008
1009         if (!pit->params().labelString().empty()) {
1010                 pit->params().labelString(string());
1011         }
1012
1013         if (layout->margintype == MARGIN_MANUAL) {
1014                 if (pit->params().labelWidthString().empty()) {
1015                         pit->setLabelWidthString(layout->labelstring());
1016                 }
1017         } else {
1018                 pit->setLabelWidthString(string());
1019         }
1020
1021         // is it a layout that has an automatic label?
1022         if (layout->labeltype >= LABEL_COUNTER_CHAPTER) {
1023                 int const i = layout->labeltype - LABEL_COUNTER_CHAPTER;
1024
1025                 ostringstream s;
1026
1027                 if (i >= 0 && i <= buf->params.secnumdepth) {
1028                         string numbertype;
1029                         string langtype;
1030
1031                         textclass.counters().step(layout->latexname());
1032
1033                         // Is there a label? Useful for Chapter layout
1034                         if (!pit->params().appendix()) {
1035                                 s << buf->B_(layout->labelstring());
1036                         } else {
1037                                 s << buf->B_(layout->labelstring_appendix());
1038                         }
1039
1040                         // Use of an integer is here less than elegant. For now.
1041                         int head = textclass.maxcounter() - LABEL_COUNTER_CHAPTER;
1042                         if (!pit->params().appendix()) {
1043                                 numbertype = "sectioning";
1044                         } else {
1045                                 numbertype = "appendix";
1046                                 if (pit->isRightToLeftPar(buf->params))
1047                                         langtype = "hebrew";
1048                                 else
1049                                         langtype = "latin";
1050                         }
1051
1052                         s << " "
1053                           << textclass.counters()
1054                                 .numberLabel(layout->latexname(),
1055                                              numbertype, langtype, head);
1056
1057                         pit->params().labelString(STRCONV(s.str()));
1058
1059                         // reset enum counters
1060                         textclass.counters().reset("enum");
1061                 } else if (layout->labeltype < LABEL_COUNTER_ENUMI) {
1062                         textclass.counters().reset("enum");
1063                 } else if (layout->labeltype == LABEL_COUNTER_ENUMI) {
1064                         // FIXME
1065                         // Yes I know this is a really, really! bad solution
1066                         // (Lgb)
1067                         string enumcounter("enum");
1068
1069                         switch (pit->enumdepth) {
1070                         case 2:
1071                                 enumcounter += 'i';
1072                         case 1:
1073                                 enumcounter += 'i';
1074                         case 0:
1075                                 enumcounter += 'i';
1076                                 break;
1077                         case 3:
1078                                 enumcounter += "iv";
1079                                 break;
1080                         default:
1081                                 // not a valid enumdepth...
1082                                 break;
1083                         }
1084
1085                         textclass.counters().step(enumcounter);
1086
1087                         s << textclass.counters()
1088                                 .numberLabel(enumcounter, "enumeration");
1089                         pit->params().labelString(STRCONV(s.str()));
1090                 }
1091         } else if (layout->labeltype == LABEL_BIBLIO) {// ale970302
1092                 textclass.counters().step("bibitem");
1093                 int number = textclass.counters().value("bibitem");
1094                 if (pit->bibitem()) {
1095                         pit->bibitem()->setCounter(number);
1096                         pit->params().labelString(layout->labelstring());
1097                 }
1098                 // In biblio should't be following counters but...
1099         } else {
1100                 string s = buf->B_(layout->labelstring());
1101
1102                 // the caption hack:
1103                 if (layout->labeltype == LABEL_SENSITIVE) {
1104                         ParagraphList::iterator end = ownerParagraphs().end();
1105                         ParagraphList::iterator tmppit = pit;
1106                         InsetOld * in = 0;
1107                         bool isOK = false;
1108                         while (tmppit != end && tmppit->inInset()
1109                                // the single '=' is intended below
1110                                && (in = tmppit->inInset()->owner()))
1111                         {
1112                                 if (in->lyxCode() == InsetOld::FLOAT_CODE ||
1113                                     in->lyxCode() == InsetOld::WRAP_CODE) {
1114                                         isOK = true;
1115                                         break;
1116                                 } else {
1117                                         tmppit = ownerParagraphs().begin();
1118                                         for ( ; tmppit != end; ++tmppit)
1119                                                 if (&*tmppit == in->parOwner())
1120                                                         break;
1121                                 }
1122                         }
1123
1124                         if (isOK) {
1125                                 string type;
1126
1127                                 if (in->lyxCode() == InsetOld::FLOAT_CODE)
1128                                         type = static_cast<InsetFloat*>(in)->params().type;
1129                                 else if (in->lyxCode() == InsetOld::WRAP_CODE)
1130                                         type = static_cast<InsetWrap*>(in)->params().type;
1131                                 else
1132                                         Assert(0);
1133
1134                                 Floating const & fl = textclass.floats().getType(type);
1135
1136                                 textclass.counters().step(fl.type());
1137
1138                                 // Doesn't work... yet.
1139                                 s = bformat(_("%1$s #:"), buf->B_(fl.name()));
1140                         } else {
1141                                 // par->SetLayout(0);
1142                                 // s = layout->labelstring;
1143                                 s = _("Senseless: ");
1144                         }
1145                 }
1146                 pit->params().labelString(s);
1147
1148                 // reset the enumeration counter. They are always reset
1149                 // when there is any other layout between
1150                 // Just fall-through between the cases so that all
1151                 // enum counters deeper than enumdepth is also reset.
1152                 switch (pit->enumdepth) {
1153                 case 0:
1154                         textclass.counters().reset("enumi");
1155                 case 1:
1156                         textclass.counters().reset("enumii");
1157                 case 2:
1158                         textclass.counters().reset("enumiii");
1159                 case 3:
1160                         textclass.counters().reset("enumiv");
1161                 }
1162         }
1163 }
1164
1165
1166 // Updates all counters. Paragraphs with changed label string will be rebroken
1167 void LyXText::updateCounters()
1168 {
1169         RowList::iterator rowit = rows().begin();
1170         ParagraphList::iterator pit = rowit->par();
1171
1172         // CHECK if this is really needed. (Lgb)
1173         bv()->buffer()->params.getLyXTextClass().counters().reset();
1174
1175         ParagraphList::iterator beg = ownerParagraphs().begin();
1176         ParagraphList::iterator end = ownerParagraphs().end();
1177         for (; pit != end; ++pit) {
1178                 while (rowit->par() != pit)
1179                         ++rowit;
1180
1181                 string const oldLabel = pit->params().labelString();
1182
1183                 size_t maxdepth = 0;
1184                 if (pit != beg)
1185                         maxdepth = boost::prior(pit)->getMaxDepthAfter();
1186
1187                 if (pit->params().depth() > maxdepth)
1188                         pit->params().depth(maxdepth);
1189
1190                 // setCounter can potentially change the labelString.
1191                 setCounter(bv()->buffer(), pit);
1192
1193                 string const & newLabel = pit->params().labelString();
1194
1195                 if (oldLabel.empty() && !newLabel.empty()) {
1196                         removeParagraph(rowit);
1197                         appendParagraph(rowit);
1198                 }
1199         }
1200 }
1201
1202
1203 void LyXText::insertInset(InsetOld * inset)
1204 {
1205         if (!cursor.par()->insetAllowed(inset->lyxCode()))
1206                 return;
1207         recordUndo(bv(), Undo::ATOMIC, cursor.par());
1208         freezeUndo();
1209         cursor.par()->insertInset(cursor.pos(), inset);
1210         // Just to rebreak and refresh correctly.
1211         // The character will not be inserted a second time
1212         insertChar(Paragraph::META_INSET);
1213         // If we enter a highly editable inset the cursor should be to before
1214         // the inset. This couldn't happen before as Undo was not handled inside
1215         // inset now after the Undo LyX tries to call inset->Edit(...) again
1216         // and cannot do this as the cursor is behind the inset and GetInset
1217         // does not return the inset!
1218         if (isHighlyEditableInset(inset)) {
1219                 cursorLeft(true);
1220         }
1221         unFreezeUndo();
1222 }
1223
1224
1225 void LyXText::cutSelection(bool doclear, bool realcut)
1226 {
1227         // Stuff what we got on the clipboard. Even if there is no selection.
1228
1229         // There is a problem with having the stuffing here in that the
1230         // larger the selection the slower LyX will get. This can be
1231         // solved by running the line below only when the selection has
1232         // finished. The solution used currently just works, to make it
1233         // faster we need to be more clever and probably also have more
1234         // calls to stuffClipboard. (Lgb)
1235         bv()->stuffClipboard(selectionAsString(bv()->buffer(), true));
1236
1237         // This doesn't make sense, if there is no selection
1238         if (!selection.set())
1239                 return;
1240
1241         // OK, we have a selection. This is always between selection.start
1242         // and selection.end
1243
1244         // make sure that the depth behind the selection are restored, too
1245         ParagraphList::iterator endpit = boost::next(selection.end.par());
1246         ParagraphList::iterator undoendpit = endpit;
1247         ParagraphList::iterator pars_end = ownerParagraphs().end();
1248
1249         if (endpit != pars_end && endpit->getDepth()) {
1250                 while (endpit != pars_end && endpit->getDepth()) {
1251                         ++endpit;
1252                         undoendpit = endpit;
1253                 }
1254         } else if (endpit != pars_end) {
1255                 // because of parindents etc.
1256                 ++endpit;
1257         }
1258
1259         recordUndo(bv(), Undo::DELETE, selection.start.par(),
1260                 boost::prior(undoendpit));
1261
1262
1263         endpit = selection.end.par();
1264         int endpos = selection.end.pos();
1265
1266         boost::tie(endpit, endpos) = realcut ?
1267                 CutAndPaste::cutSelection(bv()->buffer()->params,
1268                                           ownerParagraphs(),
1269                                           selection.start.par(), endpit,
1270                                           selection.start.pos(), endpos,
1271                                           bv()->buffer()->params.textclass,
1272                                           doclear)
1273                 : CutAndPaste::eraseSelection(bv()->buffer()->params,
1274                                               ownerParagraphs(),
1275                                               selection.start.par(), endpit,
1276                                               selection.start.pos(), endpos,
1277                                               doclear);
1278         // sometimes necessary
1279         if (doclear)
1280                 selection.start.par()->stripLeadingSpaces();
1281
1282         redoParagraphs(selection.start, boost::next(endpit));
1283 #warning FIXME latent bug
1284         // endpit will be invalidated on redoParagraphs once ParagraphList
1285         // becomes a std::list? There are maybe other places on which this
1286         // can happend? (Ab)
1287         // cutSelection can invalidate the cursor so we need to set
1288         // it anew. (Lgb)
1289         // we prefer the end for when tracking changes
1290         cursor.pos(endpos);
1291         cursor.par(endpit);
1292
1293         // need a valid cursor. (Lgb)
1294         clearSelection();
1295
1296         setCursor(cursor.par(), cursor.pos());
1297         selection.cursor = cursor;
1298         updateCounters();
1299 }
1300
1301
1302 void LyXText::copySelection()
1303 {
1304         // stuff the selection onto the X clipboard, from an explicit copy request
1305         bv()->stuffClipboard(selectionAsString(bv()->buffer(), true));
1306
1307         // this doesnt make sense, if there is no selection
1308         if (!selection.set())
1309                 return;
1310
1311         // ok we have a selection. This is always between selection.start
1312         // and sel_end cursor
1313
1314         // copy behind a space if there is one
1315         while (selection.start.par()->size() > selection.start.pos()
1316                && selection.start.par()->isLineSeparator(selection.start.pos())
1317                && (selection.start.par() != selection.end.par()
1318                    || selection.start.pos() < selection.end.pos()))
1319                 selection.start.pos(selection.start.pos() + 1);
1320
1321         CutAndPaste::copySelection(selection.start.par(),
1322                                    selection.end.par(),
1323                                    selection.start.pos(), selection.end.pos(),
1324                                    bv()->buffer()->params.textclass);
1325 }
1326
1327
1328 void LyXText::pasteSelection(size_t sel_index)
1329 {
1330         // this does not make sense, if there is nothing to paste
1331         if (!CutAndPaste::checkPastePossible())
1332                 return;
1333
1334         recordUndo(bv(), Undo::INSERT, cursor.par());
1335
1336         ParagraphList::iterator endpit;
1337         PitPosPair ppp;
1338
1339         ErrorList el;
1340
1341         boost::tie(ppp, endpit) =
1342                 CutAndPaste::pasteSelection(*bv()->buffer(),
1343                                             ownerParagraphs(),
1344                                             cursor.par(), cursor.pos(),
1345                                             bv()->buffer()->params.textclass,
1346                                             sel_index, el);
1347         bufferErrors(*bv()->buffer(), el);
1348         bv()->showErrorList(_("Paste"));
1349
1350         redoParagraphs(cursor, endpit);
1351
1352         setCursor(cursor.par(), cursor.pos());
1353         clearSelection();
1354
1355         selection.cursor = cursor;
1356         setCursor(ppp.first, ppp.second);
1357         setSelection();
1358         updateCounters();
1359 }
1360
1361
1362 void LyXText::setSelectionRange(lyx::pos_type length)
1363 {
1364         if (!length)
1365                 return;
1366
1367         selection.cursor = cursor;
1368         while (length--)
1369                 cursorRight(bv());
1370         setSelection();
1371 }
1372
1373
1374 // simple replacing. The font of the first selected character is used
1375 void LyXText::replaceSelectionWithString(string const & str)
1376 {
1377         recordUndo(bv(), Undo::ATOMIC);
1378         freezeUndo();
1379
1380         if (!selection.set()) { // create a dummy selection
1381                 selection.end = cursor;
1382                 selection.start = cursor;
1383         }
1384
1385         // Get font setting before we cut
1386         pos_type pos = selection.end.pos();
1387         LyXFont const font = selection.start.par()
1388                 ->getFontSettings(bv()->buffer()->params,
1389                                   selection.start.pos());
1390
1391         // Insert the new string
1392         string::const_iterator cit = str.begin();
1393         string::const_iterator end = str.end();
1394         for (; cit != end; ++cit) {
1395                 selection.end.par()->insertChar(pos, (*cit), font);
1396                 ++pos;
1397         }
1398
1399         // Cut the selection
1400         cutSelection(true, false);
1401
1402         unFreezeUndo();
1403 }
1404
1405
1406 // needed to insert the selection
1407 void LyXText::insertStringAsLines(string const & str)
1408 {
1409         ParagraphList::iterator pit = cursor.par();
1410         pos_type pos = cursor.pos();
1411         ParagraphList::iterator endpit = boost::next(cursor.par());
1412
1413         recordUndo(bv(), Undo::ATOMIC);
1414
1415         // only to be sure, should not be neccessary
1416         clearSelection();
1417
1418         bv()->buffer()->insertStringAsLines(pit, pos, current_font, str);
1419
1420         redoParagraphs(cursor, endpit);
1421         setCursor(cursor.par(), cursor.pos());
1422         selection.cursor = cursor;
1423         setCursor(pit, pos);
1424         setSelection();
1425 }
1426
1427
1428 // turns double-CR to single CR, others where converted into one
1429 // blank. Then InsertStringAsLines is called
1430 void LyXText::insertStringAsParagraphs(string const & str)
1431 {
1432         string linestr(str);
1433         bool newline_inserted = false;
1434         string::size_type const siz = linestr.length();
1435
1436         for (string::size_type i = 0; i < siz; ++i) {
1437                 if (linestr[i] == '\n') {
1438                         if (newline_inserted) {
1439                                 // we know that \r will be ignored by
1440                                 // InsertStringA. Of course, it is a dirty
1441                                 // trick, but it works...
1442                                 linestr[i - 1] = '\r';
1443                                 linestr[i] = '\n';
1444                         } else {
1445                                 linestr[i] = ' ';
1446                                 newline_inserted = true;
1447                         }
1448                 } else if (IsPrintable(linestr[i])) {
1449                         newline_inserted = false;
1450                 }
1451         }
1452         insertStringAsLines(linestr);
1453 }
1454
1455
1456 void LyXText::checkParagraph(ParagraphList::iterator pit, pos_type pos)
1457 {
1458         breakAgain(getRow(pit, pos));
1459         postPaint();
1460         setCursorIntern(cursor.par(), cursor.pos(), false, cursor.boundary());
1461 }
1462
1463
1464 // returns false if inset wasn't found
1465 bool LyXText::updateInset(InsetOld * inset)
1466 {
1467         // first check the current paragraph
1468         int pos = cursor.par()->getPositionOfInset(inset);
1469         if (pos != -1) {
1470                 checkParagraph(cursor.par(), pos);
1471                 return true;
1472         }
1473
1474         // check every paragraph
1475         ParagraphList::iterator par = ownerParagraphs().begin();
1476         ParagraphList::iterator end = ownerParagraphs().end();
1477         for (; par != end; ++par) {
1478                 pos = par->getPositionOfInset(inset);
1479                 if (pos != -1) {
1480                         checkParagraph(par, pos);
1481                         return true;
1482                 }
1483         }
1484
1485         return false;
1486 }
1487
1488
1489 bool LyXText::setCursor(ParagraphList::iterator pit,
1490                         pos_type pos,
1491                         bool setfont, bool boundary)
1492 {
1493         LyXCursor old_cursor = cursor;
1494         setCursorIntern(pit, pos, setfont, boundary);
1495         return deleteEmptyParagraphMechanism(old_cursor);
1496 }
1497
1498
1499 void LyXText::setCursor(LyXCursor & cur, ParagraphList::iterator pit,
1500                         pos_type pos, bool boundary)
1501 {
1502         Assert(pit != ownerParagraphs().end());
1503
1504         cur.par(pit);
1505         cur.pos(pos);
1506         cur.boundary(boundary);
1507         if (rows().empty())
1508                 return;
1509
1510         // get the cursor y position in text
1511         int y = 0;
1512         RowList::iterator row = getRow(pit, pos, y);
1513         RowList::iterator beg = rows().begin();
1514
1515         RowList::iterator old_row = row;
1516         // if we are before the first char of this row and are still in the
1517         // same paragraph and there is a previous row then put the cursor on
1518         // the end of the previous row
1519         cur.iy(y + row->baseline());
1520         if (row != beg &&
1521             pos &&
1522             boost::prior(row)->par() == row->par() &&
1523             pos < pit->size() &&
1524             pit->getChar(pos) == Paragraph::META_INSET) {
1525                 InsetOld * ins = pit->getInset(pos);
1526                 if (ins && (ins->needFullRow() || ins->display())) {
1527                         --row;
1528                         y -= row->height();
1529                 }
1530         }
1531
1532         // y is now the beginning of the cursor row
1533         y += row->baseline();
1534         // y is now the cursor baseline
1535         cur.y(y);
1536
1537         pos_type last = lastPrintablePos(*this, old_row);
1538
1539         // None of these should happen, but we're scaredy-cats
1540         if (pos > pit->size()) {
1541                 lyxerr << "dont like 1 please report" << endl;
1542                 pos = 0;
1543                 cur.pos(0);
1544         } else if (pos > last + 1) {
1545                 lyxerr << "dont like 2 please report" << endl;
1546                 // This shouldn't happen.
1547                 pos = last + 1;
1548                 cur.pos(pos);
1549         } else if (pos < row->pos()) {
1550                 lyxerr << "dont like 3 please report" << endl;
1551                 pos = row->pos();
1552                 cur.pos(pos);
1553         }
1554
1555         // now get the cursors x position
1556         float x = getCursorX(row, pos, last, boundary);
1557         cur.x(int(x));
1558         cur.x_fix(cur.x());
1559         if (old_row != row) {
1560                 x = getCursorX(old_row, pos, last, boundary);
1561                 cur.ix(int(x));
1562         } else
1563                 cur.ix(cur.x());
1564 /* We take out this for the time being because 1) the redraw code is not
1565    prepared to this yet and 2) because some good policy has yet to be decided
1566    while editting: for instance how to act on rows being created/deleted
1567    because of DEPM.
1568 */
1569 #if 0
1570         //if the cursor is in a visible row, anchor to it
1571         int topy = top_y();
1572         if (topy < y && y < topy + bv()->workHeight())
1573                 anchor_row(row);
1574 #endif
1575 }
1576
1577
1578 float LyXText::getCursorX(RowList::iterator rit,
1579                           pos_type pos, pos_type last, bool boundary) const
1580 {
1581         pos_type cursor_vpos = 0;
1582         double x;
1583         double fill_separator;
1584         double fill_hfill;
1585         double fill_label_hfill;
1586         // This call HAS to be here because of the BidiTables!!!
1587         prepareToPrint(rit, x, fill_separator, fill_hfill,
1588                        fill_label_hfill);
1589
1590         ParagraphList::iterator rit_par = rit->par();
1591         pos_type const rit_pos = rit->pos();
1592
1593         if (last < rit_pos)
1594                 cursor_vpos = rit_pos;
1595         else if (pos > last && !boundary)
1596                 cursor_vpos = (rit_par->isRightToLeftPar(bv()->buffer()->params))
1597                         ? rit_pos : last + 1;
1598         else if (pos > rit_pos && (pos > last || boundary))
1599                 /// Place cursor after char at (logical) position pos - 1
1600                 cursor_vpos = (bidi_level(pos - 1) % 2 == 0)
1601                         ? log2vis(pos - 1) + 1 : log2vis(pos - 1);
1602         else
1603                 /// Place cursor before char at (logical) position pos
1604                 cursor_vpos = (bidi_level(pos) % 2 == 0)
1605                         ? log2vis(pos) : log2vis(pos) + 1;
1606
1607         pos_type body_pos = rit_par->beginningOfBody();
1608         if (body_pos > 0 &&
1609             (body_pos - 1 > last || !rit_par->isLineSeparator(body_pos - 1)))
1610                 body_pos = 0;
1611
1612         for (pos_type vpos = rit_pos; vpos < cursor_vpos; ++vpos) {
1613                 pos_type pos = vis2log(vpos);
1614                 if (body_pos > 0 && pos == body_pos - 1) {
1615                         x += fill_label_hfill +
1616                                 font_metrics::width(
1617                                         rit_par->layout()->labelsep, getLabelFont(rit_par));
1618                         if (rit_par->isLineSeparator(body_pos - 1))
1619                                 x -= singleWidth(rit_par, body_pos - 1);
1620                 }
1621
1622                 if (hfillExpansion(*this, rit, pos)) {
1623                         x += singleWidth(rit_par, pos);
1624                         if (pos >= body_pos)
1625                                 x += fill_hfill;
1626                         else
1627                                 x += fill_label_hfill;
1628                 } else if (rit_par->isSeparator(pos)) {
1629                         x += singleWidth(rit_par, pos);
1630                         if (pos >= body_pos)
1631                                 x += fill_separator;
1632                 } else
1633                         x += singleWidth(rit_par, pos);
1634         }
1635         return x;
1636 }
1637
1638
1639 void LyXText::setCursorIntern(ParagraphList::iterator pit,
1640                               pos_type pos, bool setfont, bool boundary)
1641 {
1642         UpdatableInset * it = pit->inInset();
1643         if (it) {
1644                 if (it != inset_owner) {
1645                         lyxerr[Debug::INSETS] << "InsetText   is " << it
1646                                               << endl
1647                                               << "inset_owner is "
1648                                               << inset_owner << endl;
1649 #ifdef WITH_WARNINGS
1650 #warning I believe this code is wrong. (Lgb)
1651 #warning Jürgen, have a look at this. (Lgb)
1652 #warning Hmmm, I guess you are right but we
1653 #warning should verify when this is needed
1654 #endif
1655                         // Jürgen, would you like to have a look?
1656                         // I guess we need to move the outer cursor
1657                         // and open and lock the inset (bla bla bla)
1658                         // stuff I don't know... so can you have a look?
1659                         // (Lgb)
1660                         // I moved the lyxerr stuff in here so we can see if
1661                         // this is actually really needed and where!
1662                         // (Jug)
1663                         // it->getLyXText(bv())->setCursorIntern(bv(), par, pos, setfont, boundary);
1664                         return;
1665                 }
1666         }
1667
1668         setCursor(cursor, pit, pos, boundary);
1669         if (setfont)
1670                 setCurrentFont();
1671 }
1672
1673
1674 void LyXText::setCurrentFont()
1675 {
1676         pos_type pos = cursor.pos();
1677         ParagraphList::iterator pit = cursor.par();
1678
1679         if (cursor.boundary() && pos > 0)
1680                 --pos;
1681
1682         if (pos > 0) {
1683                 if (pos == pit->size())
1684                         --pos;
1685                 else // potentional bug... BUG (Lgb)
1686                         if (pit->isSeparator(pos)) {
1687                                 if (pos > cursorRow()->pos() &&
1688                                     bidi_level(pos) % 2 ==
1689                                     bidi_level(pos - 1) % 2)
1690                                         --pos;
1691                                 else if (pos + 1 < pit->size())
1692                                         ++pos;
1693                         }
1694         }
1695
1696         current_font = pit->getFontSettings(bv()->buffer()->params, pos);
1697         real_current_font = getFont(pit, pos);
1698
1699         if (cursor.pos() == pit->size() &&
1700             isBoundary(bv()->buffer(), *pit, cursor.pos()) &&
1701             !cursor.boundary()) {
1702                 Language const * lang =
1703                         pit->getParLanguage(bv()->buffer()->params);
1704                 current_font.setLanguage(lang);
1705                 current_font.setNumber(LyXFont::OFF);
1706                 real_current_font.setLanguage(lang);
1707                 real_current_font.setNumber(LyXFont::OFF);
1708         }
1709 }
1710
1711
1712 // returns the column near the specified x-coordinate of the row
1713 // x is set to the real beginning of this column
1714 pos_type
1715 LyXText::getColumnNearX(RowList::iterator rit, int & x, bool & boundary) const
1716 {
1717         double tmpx = 0;
1718         double fill_separator;
1719         double fill_hfill;
1720         double fill_label_hfill;
1721
1722         prepareToPrint(rit, tmpx, fill_separator, fill_hfill, fill_label_hfill);
1723
1724         pos_type vc = rit->pos();
1725         pos_type last = lastPrintablePos(*this, rit);
1726         pos_type c = 0;
1727
1728         ParagraphList::iterator rit_par = rit->par();
1729         LyXLayout_ptr const & layout = rit->par()->layout();
1730
1731         bool left_side = false;
1732
1733         pos_type body_pos = rit_par->beginningOfBody();
1734         double last_tmpx = tmpx;
1735
1736         if (body_pos > 0 &&
1737             (body_pos - 1 > last ||
1738              !rit_par->isLineSeparator(body_pos - 1)))
1739                 body_pos = 0;
1740
1741         // check for empty row
1742         if (!rit_par->size()) {
1743                 x = int(tmpx);
1744                 return 0;
1745         }
1746
1747         while (vc <= last && tmpx <= x) {
1748                 c = vis2log(vc);
1749                 last_tmpx = tmpx;
1750                 if (body_pos > 0 && c == body_pos - 1) {
1751                         tmpx += fill_label_hfill +
1752                                 font_metrics::width(layout->labelsep, getLabelFont(rit_par));
1753                         if (rit_par->isLineSeparator(body_pos - 1))
1754                                 tmpx -= singleWidth(rit_par, body_pos - 1);
1755                 }
1756
1757                 if (hfillExpansion(*this, rit, c)) {
1758                         tmpx += singleWidth(rit_par, c);
1759                         if (c >= body_pos)
1760                                 tmpx += fill_hfill;
1761                         else
1762                                 tmpx += fill_label_hfill;
1763                 } else if (rit_par->isSeparator(c)) {
1764                         tmpx += singleWidth(rit_par, c);
1765                         if (c >= body_pos)
1766                                 tmpx += fill_separator;
1767                 } else {
1768                         tmpx += singleWidth(rit_par, c);
1769                 }
1770                 ++vc;
1771         }
1772
1773         if ((tmpx + last_tmpx) / 2 > x) {
1774                 tmpx = last_tmpx;
1775                 left_side = true;
1776         }
1777
1778         if (vc > last + 1)  // This shouldn't happen.
1779                 vc = last + 1;
1780
1781         boundary = false;
1782         // This (rtl_support test) is not needed, but gives
1783         // some speedup if rtl_support=false
1784         RowList::iterator next_rit = boost::next(rit);
1785
1786         bool const lastrow = lyxrc.rtl_support &&
1787                 (next_rit == rowlist_.end() ||
1788                  next_rit->par() != rit_par);
1789
1790         // If lastrow is false, we don't need to compute
1791         // the value of rtl.
1792         bool const rtl = (lastrow)
1793                 ? rit_par->isRightToLeftPar(bv()->buffer()->params)
1794                 : false;
1795         if (lastrow &&
1796                  ((rtl &&  left_side && vc == rit->pos() && x < tmpx - 5) ||
1797                    (!rtl && !left_side && vc == last + 1   && x > tmpx + 5)))
1798                 c = last + 1;
1799         else if (vc == rit->pos()) {
1800                 c = vis2log(vc);
1801                 if (bidi_level(c) % 2 == 1)
1802                         ++c;
1803         } else {
1804                 c = vis2log(vc - 1);
1805                 bool const rtl = (bidi_level(c) % 2 == 1);
1806                 if (left_side == rtl) {
1807                         ++c;
1808                         boundary = isBoundary(bv()->buffer(), *rit_par, c);
1809                 }
1810         }
1811
1812         if (rit->pos() <= last && c > last
1813             && rit_par->isNewline(last)) {
1814                 if (bidi_level(last) % 2 == 0)
1815                         tmpx -= singleWidth(rit_par, last);
1816                 else
1817                         tmpx += singleWidth(rit_par, last);
1818                 c = last;
1819         }
1820
1821         c -= rit->pos();
1822         x = int(tmpx);
1823         return c;
1824 }
1825
1826
1827 void LyXText::setCursorFromCoordinates(int x, int y)
1828 {
1829         //LyXCursor old_cursor = cursor;
1830         setCursorFromCoordinates(cursor, x, y);
1831         setCurrentFont();
1832 #warning DEPM disabled, otherwise crash when entering new table
1833         //deleteEmptyParagraphMechanism(old_cursor);
1834 }
1835
1836
1837 namespace {
1838
1839         /**
1840          * return true if the cursor given is at the end of a row,
1841          * and the next row is filled by an inset that spans an entire
1842          * row.
1843          */
1844         bool beforeFullRowInset(LyXText & lt, LyXCursor const & cur)
1845         {
1846                 RowList::iterator row = lt.getRow(cur);
1847                 if (boost::next(row) == lt.rows().end())
1848                         return false;
1849
1850                 Row const & next = *boost::next(row);
1851
1852                 if (next.pos() != cur.pos() || next.par() != cur.par())
1853                         return false;
1854
1855                 if (cur.pos() == cur.par()->size()
1856                     || !cur.par()->isInset(cur.pos()))
1857                         return false;
1858
1859                 InsetOld const * inset = cur.par()->getInset(cur.pos());
1860                 if (inset->needFullRow() || inset->display())
1861                         return true;
1862
1863                 return false;
1864         }
1865 }
1866
1867
1868 void LyXText::setCursorFromCoordinates(LyXCursor & cur, int x, int y)
1869 {
1870         // Get the row first.
1871
1872         RowList::iterator row = getRowNearY(y);
1873         bool bound = false;
1874         pos_type const column = getColumnNearX(row, x, bound);
1875         cur.par(row->par());
1876         cur.pos(row->pos() + column);
1877         cur.x(x);
1878         cur.y(y + row->baseline());
1879
1880         if (beforeFullRowInset(*this, cur)) {
1881                 pos_type const last = lastPrintablePos(*this, row);
1882                 RowList::iterator next_row = boost::next(row);
1883
1884                 float x = getCursorX(next_row, cur.pos(), last, bound);
1885                 cur.ix(int(x));
1886                 cur.iy(y + row->height() + next_row->baseline());
1887         } else {
1888                 cur.iy(cur.y());
1889                 cur.ix(cur.x());
1890         }
1891         cur.boundary(bound);
1892 }
1893
1894
1895 void LyXText::cursorLeft(bool internal)
1896 {
1897         if (cursor.pos() > 0) {
1898                 bool boundary = cursor.boundary();
1899                 setCursor(cursor.par(), cursor.pos() - 1, true, false);
1900                 if (!internal && !boundary &&
1901                     isBoundary(bv()->buffer(), *cursor.par(), cursor.pos() + 1))
1902                         setCursor(cursor.par(), cursor.pos() + 1, true, true);
1903         } else if (cursor.par() != ownerParagraphs().begin()) { // steps into the above paragraph.
1904                 ParagraphList::iterator pit = boost::prior(cursor.par());
1905                 setCursor(pit, pit->size());
1906         }
1907 }
1908
1909
1910 void LyXText::cursorRight(bool internal)
1911 {
1912         bool const at_end = (cursor.pos() == cursor.par()->size());
1913         bool const at_newline = !at_end &&
1914                 cursor.par()->isNewline(cursor.pos());
1915
1916         if (!internal && cursor.boundary() && !at_newline)
1917                 setCursor(cursor.par(), cursor.pos(), true, false);
1918         else if (!at_end) {
1919                 setCursor(cursor.par(), cursor.pos() + 1, true, false);
1920                 if (!internal &&
1921                     isBoundary(bv()->buffer(), *cursor.par(), cursor.pos()))
1922                         setCursor(cursor.par(), cursor.pos(), true, true);
1923         } else if (boost::next(cursor.par()) != ownerParagraphs().end())
1924                 setCursor(boost::next(cursor.par()), 0);
1925 }
1926
1927
1928 void LyXText::cursorUp(bool selecting)
1929 {
1930 #if 1
1931         int x = cursor.x_fix();
1932         int y = cursor.y() - cursorRow()->baseline() - 1;
1933         setCursorFromCoordinates(x, y);
1934         if (!selecting) {
1935                 int topy = top_y();
1936                 int y1 = cursor.iy() - topy;
1937                 int y2 = y1;
1938                 y -= topy;
1939                 InsetOld * inset_hit = checkInsetHit(x, y1);
1940                 if (inset_hit && isHighlyEditableInset(inset_hit)) {
1941                         inset_hit->localDispatch(
1942                                 FuncRequest(bv(), LFUN_INSET_EDIT, x, y - (y2 - y1), mouse_button::none));
1943                 }
1944         }
1945 #else
1946         setCursorFromCoordinates(bv(), cursor.x_fix(),
1947                                  cursor.y() - cursorRow()->baseline() - 1);
1948 #endif
1949 }
1950
1951
1952 void LyXText::cursorDown(bool selecting)
1953 {
1954 #if 1
1955         int x = cursor.x_fix();
1956         int y = cursor.y() - cursorRow()->baseline() + cursorRow()->height() + 1;
1957         setCursorFromCoordinates(x, y);
1958         if (!selecting && cursorRow() == cursorIRow()) {
1959                 int topy = top_y();
1960                 int y1 = cursor.iy() - topy;
1961                 int y2 = y1;
1962                 y -= topy;
1963                 InsetOld * inset_hit = checkInsetHit(x, y1);
1964                 if (inset_hit && isHighlyEditableInset(inset_hit)) {
1965                         FuncRequest cmd(bv(), LFUN_INSET_EDIT, x, y - (y2 - y1), mouse_button::none);
1966                         inset_hit->localDispatch(cmd);
1967                 }
1968         }
1969 #else
1970         setCursorFromCoordinates(bv(), cursor.x_fix(),
1971                                  cursor.y() - cursorRow()->baseline()
1972                                  + cursorRow()->height() + 1);
1973 #endif
1974 }
1975
1976
1977 void LyXText::cursorUpParagraph()
1978 {
1979         if (cursor.pos() > 0) {
1980                 setCursor(cursor.par(), 0);
1981         }
1982         else if (cursor.par() != ownerParagraphs().begin()) {
1983                 setCursor(boost::prior(cursor.par()), 0);
1984         }
1985 }
1986
1987
1988 void LyXText::cursorDownParagraph()
1989 {
1990         ParagraphList::iterator par = cursor.par();
1991         ParagraphList::iterator next_par = boost::next(par);
1992
1993         if (next_par != ownerParagraphs().end()) {
1994                 setCursor(next_par, 0);
1995         } else {
1996                 setCursor(par, par->size());
1997         }
1998 }
1999
2000 // fix the cursor `cur' after a characters has been deleted at `where'
2001 // position. Called by deleteEmptyParagraphMechanism
2002 void LyXText::fixCursorAfterDelete(LyXCursor & cur,
2003                                    LyXCursor const & where)
2004 {
2005         // if cursor is not in the paragraph where the delete occured,
2006         // do nothing
2007         if (cur.par() != where.par())
2008                 return;
2009
2010         // if cursor position is after the place where the delete occured,
2011         // update it
2012         if (cur.pos() > where.pos())
2013                 cur.pos(cur.pos()-1);
2014
2015         // check also if we don't want to set the cursor on a spot behind the
2016         // pagragraph because we erased the last character.
2017         if (cur.pos() > cur.par()->size())
2018                 cur.pos(cur.par()->size());
2019
2020         // recompute row et al. for this cursor
2021         setCursor(cur, cur.par(), cur.pos(), cur.boundary());
2022 }
2023
2024
2025 bool LyXText::deleteEmptyParagraphMechanism(LyXCursor const & old_cursor)
2026 {
2027         // Would be wrong to delete anything if we have a selection.
2028         if (selection.set())
2029                 return false;
2030
2031         // We allow all kinds of "mumbo-jumbo" when freespacing.
2032         if (old_cursor.par()->layout()->free_spacing
2033             || old_cursor.par()->isFreeSpacing()) {
2034                 return false;
2035         }
2036
2037         /* Ok I'll put some comments here about what is missing.
2038            I have fixed BackSpace (and thus Delete) to not delete
2039            double-spaces automagically. I have also changed Cut,
2040            Copy and Paste to hopefully do some sensible things.
2041            There are still some small problems that can lead to
2042            double spaces stored in the document file or space at
2043            the beginning of paragraphs. This happens if you have
2044            the cursor betwenn to spaces and then save. Or if you
2045            cut and paste and the selection have a space at the
2046            beginning and then save right after the paste. I am
2047            sure none of these are very hard to fix, but I will
2048            put out 1.1.4pre2 with FIX_DOUBLE_SPACE defined so
2049            that I can get some feedback. (Lgb)
2050         */
2051
2052         // If old_cursor.pos() == 0 and old_cursor.pos()(1) == LineSeparator
2053         // delete the LineSeparator.
2054         // MISSING
2055
2056         // If old_cursor.pos() == 1 and old_cursor.pos()(0) == LineSeparator
2057         // delete the LineSeparator.
2058         // MISSING
2059
2060         // If the pos around the old_cursor were spaces, delete one of them.
2061         if (old_cursor.par() != cursor.par()
2062             || old_cursor.pos() != cursor.pos()) {
2063                 // Only if the cursor has really moved
2064
2065                 if (old_cursor.pos() > 0
2066                     && old_cursor.pos() < old_cursor.par()->size()
2067                     && old_cursor.par()->isLineSeparator(old_cursor.pos())
2068                     && old_cursor.par()->isLineSeparator(old_cursor.pos() - 1)) {
2069                         old_cursor.par()->erase(old_cursor.pos() - 1);
2070                         redoParagraphs(old_cursor, boost::next(old_cursor.par()));
2071
2072 #ifdef WITH_WARNINGS
2073 #warning This will not work anymore when we have multiple views of the same buffer
2074 // In this case, we will have to correct also the cursors held by
2075 // other bufferviews. It will probably be easier to do that in a more
2076 // automated way in LyXCursor code. (JMarc 26/09/2001)
2077 #endif
2078                         // correct all cursors held by the LyXText
2079                         fixCursorAfterDelete(cursor, old_cursor);
2080                         fixCursorAfterDelete(selection.cursor, old_cursor);
2081                         fixCursorAfterDelete(selection.start, old_cursor);
2082                         fixCursorAfterDelete(selection.end, old_cursor);
2083                         fixCursorAfterDelete(last_sel_cursor, old_cursor);
2084                         return false;
2085                 }
2086         }
2087
2088         // don't delete anything if this is the ONLY paragraph!
2089         if (ownerParagraphs().size() == 1)
2090                 return false;
2091
2092         // Do not delete empty paragraphs with keepempty set.
2093         if (old_cursor.par()->allowEmpty())
2094                 return false;
2095
2096         // only do our magic if we changed paragraph
2097         if (old_cursor.par() == cursor.par())
2098                 return false;
2099
2100         // record if we have deleted a paragraph
2101         // we can't possibly have deleted a paragraph before this point
2102         bool deleted = false;
2103
2104         if (old_cursor.par()->empty() ||
2105             (old_cursor.par()->size() == 1 &&
2106              old_cursor.par()->isLineSeparator(0))) {
2107                 // ok, we will delete anything
2108                 LyXCursor tmpcursor;
2109
2110                 deleted = true;
2111
2112                 bool selection_position_was_oldcursor_position = (
2113                         selection.cursor.par()  == old_cursor.par()
2114                         && selection.cursor.pos() == old_cursor.pos());
2115
2116                 if (getRow(old_cursor) != rows().begin()) {
2117                         RowList::iterator prevrow = boost::prior(getRow(old_cursor));
2118                         postPaint();
2119                         tmpcursor = cursor;
2120                         cursor = old_cursor; // that undo can restore the right cursor position
2121                         #warning FIXME. --end() iterator is usable here
2122                         ParagraphList::iterator endpit = boost::next(old_cursor.par());
2123                         while (endpit != ownerParagraphs().end() &&
2124                                endpit->getDepth()) {
2125                                 ++endpit;
2126                         }
2127
2128                         recordUndo(bv(), Undo::DELETE, old_cursor.par(),
2129                                 boost::prior(endpit));
2130                         cursor = tmpcursor;
2131
2132                         // delete old row
2133                         removeRow(getRow(old_cursor));
2134                         // delete old par
2135                         ownerParagraphs().erase(old_cursor.par());
2136
2137                         /* Breakagain the next par. Needed because of
2138                          * the parindent that can occur or dissappear.
2139                          * The next row can change its height, if
2140                          * there is another layout before */
2141                         RowList::iterator tmprit = boost::next(prevrow);
2142                         if (tmprit != rows().end()) {
2143                                 breakAgain(tmprit);
2144                                 updateCounters();
2145                         }
2146                         setHeightOfRow(prevrow);
2147                 } else {
2148                         RowList::iterator nextrow = boost::next(getRow(old_cursor));
2149                         postPaint();
2150
2151                         tmpcursor = cursor;
2152                         cursor = old_cursor; // that undo can restore the right cursor position
2153 #warning FIXME. --end() iterator is usable here
2154                         ParagraphList::iterator endpit = boost::next(old_cursor.par());
2155                         while (endpit != ownerParagraphs().end() &&
2156                                endpit->getDepth()) {
2157                                 ++endpit;
2158                         }
2159
2160                         recordUndo(bv(), Undo::DELETE, old_cursor.par(), boost::prior(endpit));
2161                         cursor = tmpcursor;
2162
2163                         // delete old row
2164                         removeRow(getRow(old_cursor));
2165                         // delete old par
2166                         ownerParagraphs().erase(old_cursor.par());
2167
2168                         /* Breakagain the next par. Needed because of
2169                            the parindent that can occur or dissappear.
2170                            The next row can change its height, if
2171                            there is another layout before */
2172                         if (nextrow != rows().end()) {
2173                                 breakAgain(nextrow);
2174                                 updateCounters();
2175                         }
2176                 }
2177
2178                 // correct cursor y
2179                 setCursorIntern(cursor.par(), cursor.pos());
2180
2181                 if (selection_position_was_oldcursor_position) {
2182                         // correct selection
2183                         selection.cursor = cursor;
2184                 }
2185         }
2186         if (!deleted) {
2187                 if (old_cursor.par()->stripLeadingSpaces()) {
2188                         redoParagraphs(old_cursor, boost::next(old_cursor.par()));
2189                         // correct cursor y
2190                         setCursorIntern(cursor.par(), cursor.pos());
2191                         selection.cursor = cursor;
2192                 }
2193         }
2194         return deleted;
2195 }
2196
2197
2198 ParagraphList & LyXText::ownerParagraphs() const
2199 {
2200         if (inset_owner) {
2201                 return inset_owner->paragraphs;
2202         }
2203         return bv_owner->buffer()->paragraphs;
2204 }
2205
2206
2207 bool LyXText::needRefresh() const
2208 {
2209         return need_refresh_;
2210 }
2211
2212
2213 void LyXText::clearPaint()
2214 {
2215         need_refresh_ = false;
2216 }
2217
2218
2219 void LyXText::postPaint()
2220 {
2221         need_refresh_ = true;
2222
2223         // We are an inset's lyxtext. Tell the top-level lyxtext
2224         // it needs to update the row we're in.
2225         if (inset_owner)
2226                 bv()->text->postPaint();
2227 }
2228
2229
2230 bool LyXText::isInInset() const
2231 {
2232         // Sub-level has non-null bv owner and
2233         // non-null inset owner.
2234         return inset_owner != 0 && bv_owner != 0;
2235 }
2236
2237
2238 int defaultRowHeight()
2239 {
2240         LyXFont const font(LyXFont::ALL_SANE);
2241         return int(font_metrics::maxAscent(font)
2242                  + font_metrics::maxDescent(font) * 1.5);
2243 }