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