]> git.lyx.org Git - lyx.git/blob - src/text2.C
d183f53934bc81bd4b4f3956ca8ab179dfc3208a
[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()
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         //current_font = getFont(bview->buffer(), pit, 0);
708
709         for (; pit != end; ++pit)
710                 insertParagraph(pit, rowlist_.end());
711
712         //setCursorIntern(rowlist_.begin()->par(), 0);
713         //selection.cursor = cursor;
714
715         //updateCounters();
716
717         //setCursorIntern(cursor.par(), cursor.pos());
718 }
719
720
721 void LyXText::partialRebreak()
722 {
723         if (rows().empty()) {
724                 init(bv());
725                 return;
726         }
727
728         RowList::iterator rows_end = rows().end();
729
730         if (need_break_row != rows_end) {
731                 breakAgain(need_break_row);
732                 need_break_row = rows_end;
733                 return;
734         }
735 }
736
737
738 // important for the screen
739
740
741 // the cursor set functions have a special mechanism. When they
742 // realize, that you left an empty paragraph, they will delete it.
743 // They also delete the corresponding row
744
745 // need the selection cursor:
746 void LyXText::setSelection()
747 {
748         bool const lsel = TextCursor::setSelection();
749
750         if (inset_owner && (selection.set() || lsel))
751                 inset_owner->setUpdateStatus(InsetText::SELECTION);
752 }
753
754
755
756 void LyXText::clearSelection()
757 {
758         TextCursor::clearSelection();
759
760         // reset this in the bv_owner!
761         if (bv_owner && bv_owner->text)
762                 bv_owner->text->xsel_cache.set(false);
763 }
764
765
766 void LyXText::cursorHome()
767 {
768         setCursor(cursor.par(), cursorRow()->pos());
769 }
770
771
772 void LyXText::cursorEnd()
773 {
774         if (cursor.par()->empty())
775                 return;
776
777         RowList::iterator rit = cursorRow();
778         RowList::iterator next_rit = boost::next(rit);
779         ParagraphList::iterator pit = rit->par();
780         pos_type last_pos = lastPos(*this, rit);
781
782         if (next_rit == rows().end() || next_rit->par() != pit) {
783                 ++last_pos;
784         } else {
785                 if (pit->empty() ||
786                     (pit->getChar(last_pos) != ' ' && !pit->isNewline(last_pos))) {
787                         ++last_pos;
788                 }
789         }
790
791         setCursor(pit, last_pos);
792 }
793
794
795 void LyXText::cursorTop()
796 {
797         setCursor(ownerParagraphs().begin(), 0);
798 }
799
800
801 void LyXText::cursorBottom()
802 {
803         ParagraphList::iterator lastpit =
804                 boost::prior(ownerParagraphs().end());
805         setCursor(lastpit, lastpit->size());
806 }
807
808
809 void LyXText::toggleFree(LyXFont const & font, bool toggleall)
810 {
811         // If the mask is completely neutral, tell user
812         if (font == LyXFont(LyXFont::ALL_IGNORE)) {
813                 // Could only happen with user style
814                 bv()->owner()->message(_("No font change defined. Use Character under the Layout menu to define font change."));
815                 return;
816         }
817
818         // Try implicit word selection
819         // If there is a change in the language the implicit word selection
820         // is disabled.
821         LyXCursor resetCursor = cursor;
822         bool implicitSelection = (font.language() == ignore_language
823                                   && font.number() == LyXFont::IGNORE)
824                 ? selectWordWhenUnderCursor(lyx::WHOLE_WORD_STRICT) : false;
825
826         // Set font
827         setFont(font, toggleall);
828
829         // Implicit selections are cleared afterwards
830         //and cursor is set to the original position.
831         if (implicitSelection) {
832                 clearSelection();
833                 cursor = resetCursor;
834                 setCursor(cursor.par(), cursor.pos());
835                 selection.cursor = cursor;
836         }
837         if (inset_owner)
838                 inset_owner->setUpdateStatus(InsetText::CURSOR_PAR);
839 }
840
841
842 string LyXText::getStringToIndex()
843 {
844         // Try implicit word selection
845         // If there is a change in the language the implicit word selection
846         // is disabled.
847         LyXCursor const reset_cursor = cursor;
848         bool const implicitSelection =
849                 selectWordWhenUnderCursor(lyx::PREVIOUS_WORD);
850
851         string idxstring;
852         if (!selection.set())
853                 bv()->owner()->message(_("Nothing to index!"));
854         else if (selection.start.par() != selection.end.par())
855                 bv()->owner()->message(_("Cannot index more than one paragraph!"));
856         else
857                 idxstring = selectionAsString(bv()->buffer(), false);
858
859         // Reset cursors to their original position.
860         cursor = reset_cursor;
861         setCursor(cursor.par(), cursor.pos());
862         selection.cursor = cursor;
863
864         // Clear the implicit selection.
865         if (implicitSelection)
866                 clearSelection();
867
868         return idxstring;
869 }
870
871
872 // the DTP switches for paragraphs. LyX will store them in the first
873 // physicla paragraph. When a paragraph is broken, the top settings rest,
874 // the bottom settings are given to the new one. So I can make shure,
875 // they do not duplicate themself and you cannnot make dirty things with
876 // them!
877
878 void LyXText::setParagraph(bool line_top, bool line_bottom,
879                            bool pagebreak_top, bool pagebreak_bottom,
880                            VSpace const & space_top,
881                            VSpace const & space_bottom,
882                            Spacing const & spacing,
883                            LyXAlignment align,
884                            string const & labelwidthstring,
885                            bool noindent)
886 {
887         LyXCursor tmpcursor = cursor;
888         if (!selection.set()) {
889                 selection.start = cursor;
890                 selection.end = cursor;
891         }
892
893         // make sure that the depth behind the selection are restored, too
894         ParagraphList::iterator endpit = boost::next(selection.end.par());
895         ParagraphList::iterator undoendpit = endpit;
896         ParagraphList::iterator pars_end = ownerParagraphs().end();
897
898         if (endpit != pars_end && endpit->getDepth()) {
899                 while (endpit != pars_end && endpit->getDepth()) {
900                         ++endpit;
901                         undoendpit = endpit;
902                 }
903         } else if (endpit != pars_end) {
904                 // because of parindents etc.
905                 ++endpit;
906         }
907
908         setUndo(bv(), Undo::EDIT, selection.start.par(),
909                 boost::prior(undoendpit));
910
911
912         ParagraphList::iterator tmppit = selection.end.par();
913
914         while (tmppit != boost::prior(selection.start.par())) {
915                 setCursor(tmppit, 0);
916
917                 ParagraphList::iterator pit = cursor.par();
918                 ParagraphParameters & params = pit->params();
919
920                 params.lineTop(line_top);
921                 params.lineBottom(line_bottom);
922                 params.pagebreakTop(pagebreak_top);
923                 params.pagebreakBottom(pagebreak_bottom);
924                 params.spaceTop(space_top);
925                 params.spaceBottom(space_bottom);
926                 params.spacing(spacing);
927                 // does the layout allow the new alignment?
928                 LyXLayout_ptr const & layout = pit->layout();
929
930                 if (align == LYX_ALIGN_LAYOUT)
931                         align = layout->align;
932                 if (align & layout->alignpossible) {
933                         if (align == layout->align)
934                                 params.align(LYX_ALIGN_LAYOUT);
935                         else
936                                 params.align(align);
937                 }
938                 pit->setLabelWidthString(labelwidthstring);
939                 params.noindent(noindent);
940                 tmppit = boost::prior(pit);
941         }
942         postPaint();
943
944         redoParagraphs(selection.start, endpit);
945
946         clearSelection();
947         setCursor(selection.start.par(), selection.start.pos());
948         selection.cursor = cursor;
949         setCursor(selection.end.par(), selection.end.pos());
950         setSelection();
951         setCursor(tmpcursor.par(), tmpcursor.pos());
952         if (inset_owner)
953                 bv()->updateInset(inset_owner);
954 }
955
956
957 // set the counter of a paragraph. This includes the labels
958 void LyXText::setCounter(Buffer const * buf, ParagraphList::iterator pit)
959 {
960         LyXTextClass const & textclass = buf->params.getLyXTextClass();
961         LyXLayout_ptr const & layout = pit->layout();
962
963         if (pit != ownerParagraphs().begin()) {
964
965                 pit->params().appendix(boost::prior(pit)->params().appendix());
966                 if (!pit->params().appendix() &&
967                     pit->params().startOfAppendix()) {
968                         pit->params().appendix(true);
969                         textclass.counters().reset();
970                 }
971                 pit->enumdepth = boost::prior(pit)->enumdepth;
972                 pit->itemdepth = boost::prior(pit)->itemdepth;
973         } else {
974                 pit->params().appendix(pit->params().startOfAppendix());
975                 pit->enumdepth = 0;
976                 pit->itemdepth = 0;
977         }
978
979         /* Maybe we have to increment the enumeration depth.
980          * BUT, enumeration in a footnote is considered in isolation from its
981          *      surrounding paragraph so don't increment if this is the
982          *      first line of the footnote
983          * AND, bibliographies can't have their depth changed ie. they
984          *      are always of depth 0
985          */
986         if (pit != ownerParagraphs().begin()
987             && boost::prior(pit)->getDepth() < pit->getDepth()
988             && boost::prior(pit)->layout()->labeltype == LABEL_COUNTER_ENUMI
989             && pit->enumdepth < 3
990             && layout->labeltype != LABEL_BIBLIO) {
991                 pit->enumdepth++;
992         }
993
994         // Maybe we have to decrement the enumeration depth, see note above
995         if (pit != ownerParagraphs().begin()
996             && boost::prior(pit)->getDepth() > pit->getDepth()
997             && layout->labeltype != LABEL_BIBLIO) {
998                 pit->enumdepth = depthHook(pit, ownerParagraphs(),
999                                            pit->getDepth())->enumdepth;
1000         }
1001
1002         if (!pit->params().labelString().empty()) {
1003                 pit->params().labelString(string());
1004         }
1005
1006         if (layout->margintype == MARGIN_MANUAL) {
1007                 if (pit->params().labelWidthString().empty()) {
1008                         pit->setLabelWidthString(layout->labelstring());
1009                 }
1010         } else {
1011                 pit->setLabelWidthString(string());
1012         }
1013
1014         // is it a layout that has an automatic label?
1015         if (layout->labeltype >= LABEL_COUNTER_CHAPTER) {
1016                 int const i = layout->labeltype - LABEL_COUNTER_CHAPTER;
1017
1018                 ostringstream s;
1019
1020                 if (i >= 0 && i <= buf->params.secnumdepth) {
1021                         string numbertype;
1022                         string langtype;
1023
1024                         textclass.counters().step(layout->latexname());
1025
1026                         // Is there a label? Useful for Chapter layout
1027                         if (!pit->params().appendix()) {
1028                                 s << buf->B_(layout->labelstring());
1029                         } else {
1030                                 s << buf->B_(layout->labelstring_appendix());
1031                         }
1032
1033                         // Use of an integer is here less than elegant. For now.
1034                         int head = textclass.maxcounter() - LABEL_COUNTER_CHAPTER;
1035                         if (!pit->params().appendix()) {
1036                                 numbertype = "sectioning";
1037                         } else {
1038                                 numbertype = "appendix";
1039                                 if (pit->isRightToLeftPar(buf->params))
1040                                         langtype = "hebrew";
1041                                 else
1042                                         langtype = "latin";
1043                         }
1044
1045                         s << " "
1046                           << textclass.counters()
1047                                 .numberLabel(layout->latexname(),
1048                                              numbertype, langtype, head);
1049
1050                         pit->params().labelString(STRCONV(s.str()));
1051
1052                         // reset enum counters
1053                         textclass.counters().reset("enum");
1054                 } else if (layout->labeltype < LABEL_COUNTER_ENUMI) {
1055                         textclass.counters().reset("enum");
1056                 } else if (layout->labeltype == LABEL_COUNTER_ENUMI) {
1057                         // FIXME
1058                         // Yes I know this is a really, really! bad solution
1059                         // (Lgb)
1060                         string enumcounter("enum");
1061
1062                         switch (pit->enumdepth) {
1063                         case 2:
1064                                 enumcounter += 'i';
1065                         case 1:
1066                                 enumcounter += 'i';
1067                         case 0:
1068                                 enumcounter += 'i';
1069                                 break;
1070                         case 3:
1071                                 enumcounter += "iv";
1072                                 break;
1073                         default:
1074                                 // not a valid enumdepth...
1075                                 break;
1076                         }
1077
1078                         textclass.counters().step(enumcounter);
1079
1080                         s << textclass.counters()
1081                                 .numberLabel(enumcounter, "enumeration");
1082                         pit->params().labelString(STRCONV(s.str()));
1083                 }
1084         } else if (layout->labeltype == LABEL_BIBLIO) {// ale970302
1085                 textclass.counters().step("bibitem");
1086                 int number = textclass.counters().value("bibitem");
1087                 if (pit->bibitem()) {
1088                         pit->bibitem()->setCounter(number);
1089                         pit->params().labelString(layout->labelstring());
1090                 }
1091                 // In biblio should't be following counters but...
1092         } else {
1093                 string s = buf->B_(layout->labelstring());
1094
1095                 // the caption hack:
1096                 if (layout->labeltype == LABEL_SENSITIVE) {
1097                         ParagraphList::iterator tmppit = pit;
1098                         Inset * in = 0;
1099                         bool isOK = false;
1100                         while (tmppit != ownerParagraphs().end() &&
1101                                tmppit->inInset()
1102                                // the single '=' is intended below
1103                                && (in = tmppit->inInset()->owner())) {
1104                                 if (in->lyxCode() == Inset::FLOAT_CODE ||
1105                                     in->lyxCode() == Inset::WRAP_CODE) {
1106                                         isOK = true;
1107                                         break;
1108                                 } else {
1109                                         tmppit = std::find(ownerParagraphs().begin(), ownerParagraphs().end(), *in->parOwner());
1110                                 }
1111                         }
1112
1113                         if (isOK) {
1114                                 string type;
1115
1116                                 if (in->lyxCode() == Inset::FLOAT_CODE)
1117                                         type = static_cast<InsetFloat*>(in)->params().type;
1118                                 else if (in->lyxCode() == Inset::WRAP_CODE)
1119                                         type = static_cast<InsetWrap*>(in)->params().type;
1120                                 else
1121                                         Assert(0);
1122
1123                                 Floating const & fl = textclass.floats().getType(type);
1124
1125                                 textclass.counters().step(fl.type());
1126
1127                                 // Doesn't work... yet.
1128                                 s = bformat(_("%1$s #:"), buf->B_(fl.name()));
1129                         } else {
1130                                 // par->SetLayout(0);
1131                                 // s = layout->labelstring;
1132                                 s = _("Senseless: ");
1133                         }
1134                 }
1135                 pit->params().labelString(s);
1136
1137                 // reset the enumeration counter. They are always reset
1138                 // when there is any other layout between
1139                 // Just fall-through between the cases so that all
1140                 // enum counters deeper than enumdepth is also reset.
1141                 switch (pit->enumdepth) {
1142                 case 0:
1143                         textclass.counters().reset("enumi");
1144                 case 1:
1145                         textclass.counters().reset("enumii");
1146                 case 2:
1147                         textclass.counters().reset("enumiii");
1148                 case 3:
1149                         textclass.counters().reset("enumiv");
1150                 }
1151         }
1152 }
1153
1154
1155 // Updates all counters. Paragraphs with changed label string will be rebroken
1156 void LyXText::updateCounters()
1157 {
1158         RowList::iterator rowit = rows().begin();
1159         ParagraphList::iterator pit = rowit->par();
1160
1161         // CHECK if this is really needed. (Lgb)
1162         bv()->buffer()->params.getLyXTextClass().counters().reset();
1163
1164         ParagraphList::iterator beg = ownerParagraphs().begin();
1165         ParagraphList::iterator end = ownerParagraphs().end();
1166         for (; pit != end; ++pit) {
1167                 while (rowit->par() != pit)
1168                         ++rowit;
1169
1170                 string const oldLabel = pit->params().labelString();
1171
1172                 size_t maxdepth = 0;
1173                 if (pit != beg)
1174                         maxdepth = boost::prior(pit)->getMaxDepthAfter();
1175
1176                 if (pit->params().depth() > maxdepth)
1177                         pit->params().depth(maxdepth);
1178
1179                 // setCounter can potentially change the labelString.
1180                 setCounter(bv()->buffer(), pit);
1181
1182                 string const & newLabel = pit->params().labelString();
1183
1184                 if (oldLabel.empty() && !newLabel.empty()) {
1185                         removeParagraph(rowit);
1186                         appendParagraph(rowit);
1187                 }
1188         }
1189 }
1190
1191
1192 void LyXText::insertInset(Inset * inset)
1193 {
1194         if (!cursor.par()->insetAllowed(inset->lyxCode()))
1195                 return;
1196         setUndo(bv(), Undo::FINISH, cursor.par());
1197         freezeUndo();
1198         cursor.par()->insertInset(cursor.pos(), inset);
1199         // Just to rebreak and refresh correctly.
1200         // The character will not be inserted a second time
1201         insertChar(Paragraph::META_INSET);
1202         // If we enter a highly editable inset the cursor should be to before
1203         // the inset. This couldn't happen before as Undo was not handled inside
1204         // inset now after the Undo LyX tries to call inset->Edit(...) again
1205         // and cannot do this as the cursor is behind the inset and GetInset
1206         // does not return the inset!
1207         if (isHighlyEditableInset(inset)) {
1208                 cursorLeft(true);
1209         }
1210         unFreezeUndo();
1211 }
1212
1213
1214 void LyXText::cutSelection(bool doclear, bool realcut)
1215 {
1216         // Stuff what we got on the clipboard. Even if there is no selection.
1217
1218         // There is a problem with having the stuffing here in that the
1219         // larger the selection the slower LyX will get. This can be
1220         // solved by running the line below only when the selection has
1221         // finished. The solution used currently just works, to make it
1222         // faster we need to be more clever and probably also have more
1223         // calls to stuffClipboard. (Lgb)
1224         bv()->stuffClipboard(selectionAsString(bv()->buffer(), true));
1225
1226         // This doesn't make sense, if there is no selection
1227         if (!selection.set())
1228                 return;
1229
1230         // OK, we have a selection. This is always between selection.start
1231         // and selection.end
1232
1233         // make sure that the depth behind the selection are restored, too
1234         ParagraphList::iterator endpit = boost::next(selection.end.par());
1235         ParagraphList::iterator undoendpit = endpit;
1236         ParagraphList::iterator pars_end = ownerParagraphs().end();
1237
1238         if (endpit != pars_end && endpit->getDepth()) {
1239                 while (endpit != pars_end && endpit->getDepth()) {
1240                         ++endpit;
1241                         undoendpit = endpit;
1242                 }
1243         } else if (endpit != pars_end) {
1244                 // because of parindents etc.
1245                 ++endpit;
1246         }
1247
1248         setUndo(bv(), Undo::DELETE, selection.start.par(),
1249                 boost::prior(undoendpit));
1250
1251
1252         endpit = selection.end.par();
1253         int endpos = selection.end.pos();
1254
1255         boost::tie(endpit, endpos) = realcut ?
1256                 CutAndPaste::cutSelection(bv()->buffer()->params,
1257                                           ownerParagraphs(),
1258                                           selection.start.par(), endpit,
1259                                           selection.start.pos(), endpos,
1260                                           bv()->buffer()->params.textclass,
1261                                           doclear)
1262                 : CutAndPaste::eraseSelection(bv()->buffer()->params,
1263                                               ownerParagraphs(),
1264                                               selection.start.par(), endpit,
1265                                               selection.start.pos(), endpos,
1266                                               doclear);
1267         // sometimes necessary
1268         if (doclear)
1269                 selection.start.par()->stripLeadingSpaces();
1270
1271         redoParagraphs(selection.start, boost::next(endpit));
1272 #warning FIXME latent bug
1273         // endpit will be invalidated on redoParagraphs once ParagraphList
1274         // becomes a std::list? There are maybe other places on which this
1275         // can happend? (Ab)
1276         // cutSelection can invalidate the cursor so we need to set
1277         // it anew. (Lgb)
1278         // we prefer the end for when tracking changes
1279         cursor.pos(endpos);
1280         cursor.par(endpit);
1281
1282         // need a valid cursor. (Lgb)
1283         clearSelection();
1284
1285         setCursor(cursor.par(), cursor.pos());
1286         selection.cursor = cursor;
1287         updateCounters();
1288 }
1289
1290
1291 void LyXText::copySelection()
1292 {
1293         // stuff the selection onto the X clipboard, from an explicit copy request
1294         bv()->stuffClipboard(selectionAsString(bv()->buffer(), true));
1295
1296         // this doesnt make sense, if there is no selection
1297         if (!selection.set())
1298                 return;
1299
1300         // ok we have a selection. This is always between selection.start
1301         // and sel_end cursor
1302
1303         // copy behind a space if there is one
1304         while (selection.start.par()->size() > selection.start.pos()
1305                && selection.start.par()->isLineSeparator(selection.start.pos())
1306                && (selection.start.par() != selection.end.par()
1307                    || selection.start.pos() < selection.end.pos()))
1308                 selection.start.pos(selection.start.pos() + 1);
1309
1310         CutAndPaste::copySelection(selection.start.par(),
1311                                    selection.end.par(),
1312                                    selection.start.pos(), selection.end.pos(),
1313                                    bv()->buffer()->params.textclass);
1314 }
1315
1316
1317 void LyXText::pasteSelection(size_t sel_index)
1318 {
1319         // this does not make sense, if there is nothing to paste
1320         if (!CutAndPaste::checkPastePossible())
1321                 return;
1322
1323         setUndo(bv(), Undo::INSERT, cursor.par());
1324
1325         ParagraphList::iterator endpit;
1326         PitPosPair ppp;
1327
1328         ErrorList el;
1329
1330         boost::tie(ppp, endpit) =
1331                 CutAndPaste::pasteSelection(*bv()->buffer(),
1332                                             ownerParagraphs(),
1333                                             cursor.par(), cursor.pos(),
1334                                             bv()->buffer()->params.textclass,
1335                                             sel_index, el);
1336         bufferErrors(*bv()->buffer(), el);
1337         bv()->showErrorList(_("Paste"));
1338
1339         redoParagraphs(cursor, endpit);
1340
1341         setCursor(cursor.par(), cursor.pos());
1342         clearSelection();
1343
1344         selection.cursor = cursor;
1345         setCursor(ppp.first, ppp.second);
1346         setSelection();
1347         updateCounters();
1348 }
1349
1350
1351 void LyXText::setSelectionRange(lyx::pos_type length)
1352 {
1353         if (!length)
1354                 return;
1355
1356         selection.cursor = cursor;
1357         while (length--)
1358                 cursorRight(bv());
1359         setSelection();
1360 }
1361
1362
1363 // simple replacing. The font of the first selected character is used
1364 void LyXText::replaceSelectionWithString(string const & str)
1365 {
1366         setCursorParUndo(bv());
1367         freezeUndo();
1368
1369         if (!selection.set()) { // create a dummy selection
1370                 selection.end = cursor;
1371                 selection.start = cursor;
1372         }
1373
1374         // Get font setting before we cut
1375         pos_type pos = selection.end.pos();
1376         LyXFont const font = selection.start.par()
1377                 ->getFontSettings(bv()->buffer()->params,
1378                                   selection.start.pos());
1379
1380         // Insert the new string
1381         string::const_iterator cit = str.begin();
1382         string::const_iterator end = str.end();
1383         for (; cit != end; ++cit) {
1384                 selection.end.par()->insertChar(pos, (*cit), font);
1385                 ++pos;
1386         }
1387
1388         // Cut the selection
1389         cutSelection(true, false);
1390
1391         unFreezeUndo();
1392 }
1393
1394
1395 // needed to insert the selection
1396 void LyXText::insertStringAsLines(string const & str)
1397 {
1398         ParagraphList::iterator pit = cursor.par();
1399         pos_type pos = cursor.pos();
1400         ParagraphList::iterator endpit = boost::next(cursor.par());
1401
1402         setCursorParUndo(bv());
1403
1404         // only to be sure, should not be neccessary
1405         clearSelection();
1406
1407         bv()->buffer()->insertStringAsLines(pit, pos, current_font, str);
1408
1409         redoParagraphs(cursor, endpit);
1410         setCursor(cursor.par(), cursor.pos());
1411         selection.cursor = cursor;
1412         setCursor(pit, pos);
1413         setSelection();
1414 }
1415
1416
1417 // turns double-CR to single CR, others where converted into one
1418 // blank. Then InsertStringAsLines is called
1419 void LyXText::insertStringAsParagraphs(string const & str)
1420 {
1421         string linestr(str);
1422         bool newline_inserted = false;
1423         string::size_type const siz = linestr.length();
1424
1425         for (string::size_type i = 0; i < siz; ++i) {
1426                 if (linestr[i] == '\n') {
1427                         if (newline_inserted) {
1428                                 // we know that \r will be ignored by
1429                                 // InsertStringA. Of course, it is a dirty
1430                                 // trick, but it works...
1431                                 linestr[i - 1] = '\r';
1432                                 linestr[i] = '\n';
1433                         } else {
1434                                 linestr[i] = ' ';
1435                                 newline_inserted = true;
1436                         }
1437                 } else if (IsPrintable(linestr[i])) {
1438                         newline_inserted = false;
1439                 }
1440         }
1441         insertStringAsLines(linestr);
1442 }
1443
1444
1445 void LyXText::checkParagraph(ParagraphList::iterator pit, pos_type pos)
1446 {
1447         LyXCursor tmpcursor;
1448
1449         pos_type z;
1450         RowList::iterator row = getRow(pit, pos);
1451         RowList::iterator beg = rows().begin();
1452
1453         // is there a break one row above
1454         if (row != beg && boost::prior(row)->par() == row->par()) {
1455                 z = rowBreakPoint(*boost::prior(row));
1456                 if (z >= row->pos()) {
1457                         // set the dimensions of the row above
1458                         postPaint();
1459
1460                         breakAgain(boost::prior(row));
1461
1462                         // set the cursor again. Otherwise
1463                         // dangling pointers are possible
1464                         setCursor(cursor.par(), cursor.pos(),
1465                                   false, cursor.boundary());
1466                         selection.cursor = cursor;
1467                         return;
1468                 }
1469         }
1470
1471         breakAgain(row);
1472         postPaint();
1473
1474         // set the cursor again. Otherwise dangling pointers are possible
1475         // also set the selection
1476
1477         if (selection.set()) {
1478                 tmpcursor = cursor;
1479                 setCursorIntern(selection.cursor.par(), selection.cursor.pos(),
1480                                 false, selection.cursor.boundary());
1481                 selection.cursor = cursor;
1482                 setCursorIntern(selection.start.par(),
1483                                 selection.start.pos(),
1484                                 false, selection.start.boundary());
1485                 selection.start = cursor;
1486                 setCursorIntern(selection.end.par(),
1487                                 selection.end.pos(),
1488                                 false, selection.end.boundary());
1489                 selection.end = cursor;
1490                 setCursorIntern(last_sel_cursor.par(),
1491                                 last_sel_cursor.pos(),
1492                                 false, last_sel_cursor.boundary());
1493                 last_sel_cursor = cursor;
1494                 cursor = tmpcursor;
1495         }
1496         setCursorIntern(cursor.par(), cursor.pos(),
1497                         false, cursor.boundary());
1498 }
1499
1500
1501 // returns false if inset wasn't found
1502 bool LyXText::updateInset(Inset * inset)
1503 {
1504         // first check the current paragraph
1505         int pos = cursor.par()->getPositionOfInset(inset);
1506         if (pos != -1) {
1507                 checkParagraph(cursor.par(), pos);
1508                 return true;
1509         }
1510
1511         // check every paragraph
1512
1513         ParagraphList::iterator par = ownerParagraphs().begin();
1514         ParagraphList::iterator end = ownerParagraphs().end();
1515         for (; par != end; ++par) {
1516                 pos = par->getPositionOfInset(inset);
1517                 if (pos != -1) {
1518                         checkParagraph(par, pos);
1519                         return true;
1520                 }
1521         };
1522
1523         return false;
1524 }
1525
1526
1527 bool LyXText::setCursor(ParagraphList::iterator pit,
1528                         pos_type pos,
1529                         bool setfont, bool boundary)
1530 {
1531         LyXCursor old_cursor = cursor;
1532         setCursorIntern(pit, pos, setfont, boundary);
1533         return deleteEmptyParagraphMechanism(old_cursor);
1534 }
1535
1536
1537 void LyXText::setCursor(LyXCursor & cur, ParagraphList::iterator pit,
1538                         pos_type pos, bool boundary)
1539 {
1540         Assert(pit != ownerParagraphs().end());
1541
1542         cur.par(pit);
1543         cur.pos(pos);
1544         cur.boundary(boundary);
1545         if (rows().empty())
1546                 return;
1547
1548         // get the cursor y position in text
1549         int y = 0;
1550         RowList::iterator row = getRow(pit, pos, y);
1551         RowList::iterator beg = rows().begin();
1552
1553         RowList::iterator old_row = row;
1554         // if we are before the first char of this row and are still in the
1555         // same paragraph and there is a previous row then put the cursor on
1556         // the end of the previous row
1557         cur.iy(y + row->baseline());
1558         if (row != beg &&
1559             pos &&
1560             boost::prior(row)->par() == row->par() &&
1561             pos < pit->size() &&
1562             pit->getChar(pos) == Paragraph::META_INSET) {
1563                 Inset * ins = pit->getInset(pos);
1564                 if (ins && (ins->needFullRow() || ins->display())) {
1565                         --row;
1566                         y -= row->height();
1567                 }
1568         }
1569
1570         // y is now the beginning of the cursor row
1571         y += row->baseline();
1572         // y is now the cursor baseline
1573         cur.y(y);
1574
1575         pos_type last = lastPrintablePos(*this, old_row);
1576
1577         // None of these should happen, but we're scaredy-cats
1578         if (pos > pit->size()) {
1579                 lyxerr << "dont like 1 please report" << endl;
1580                 pos = 0;
1581                 cur.pos(0);
1582         } else if (pos > last + 1) {
1583                 lyxerr << "dont like 2 please report" << endl;
1584                 // This shouldn't happen.
1585                 pos = last + 1;
1586                 cur.pos(pos);
1587         } else if (pos < row->pos()) {
1588                 lyxerr << "dont like 3 please report" << endl;
1589                 pos = row->pos();
1590                 cur.pos(pos);
1591         }
1592
1593         // now get the cursors x position
1594         float x = getCursorX(row, pos, last, boundary);
1595         cur.x(int(x));
1596         cur.x_fix(cur.x());
1597         if (old_row != row) {
1598                 x = getCursorX(old_row, pos, last, boundary);
1599                 cur.ix(int(x));
1600         } else
1601                 cur.ix(cur.x());
1602 /* We take out this for the time being because 1) the redraw code is not
1603    prepared to this yet and 2) because some good policy has yet to be decided
1604    while editting: for instance how to act on rows being created/deleted
1605    because of DEPM.
1606 */
1607 #if 0
1608         //if the cursor is in a visible row, anchor to it
1609         int topy = top_y();
1610         if (topy < y && y < topy + bv()->workHeight())
1611                 anchor_row(row);
1612 #endif
1613 }
1614
1615
1616 float LyXText::getCursorX(RowList::iterator rit,
1617                           pos_type pos, pos_type last, bool boundary) const
1618 {
1619         pos_type cursor_vpos = 0;
1620         float x;
1621         float fill_separator;
1622         float fill_hfill;
1623         float fill_label_hfill;
1624         // This call HAS to be here because of the BidiTables!!!
1625         prepareToPrint(rit, x, fill_separator, fill_hfill,
1626                        fill_label_hfill);
1627
1628         ParagraphList::iterator rit_par = rit->par();
1629         pos_type const rit_pos = rit->pos();
1630
1631         if (last < rit_pos)
1632                 cursor_vpos = rit_pos;
1633         else if (pos > last && !boundary)
1634                 cursor_vpos = (rit_par->isRightToLeftPar(bv()->buffer()->params))
1635                         ? rit_pos : last + 1;
1636         else if (pos > rit_pos && (pos > last || boundary))
1637                 /// Place cursor after char at (logical) position pos - 1
1638                 cursor_vpos = (bidi_level(pos - 1) % 2 == 0)
1639                         ? log2vis(pos - 1) + 1 : log2vis(pos - 1);
1640         else
1641                 /// Place cursor before char at (logical) position pos
1642                 cursor_vpos = (bidi_level(pos) % 2 == 0)
1643                         ? log2vis(pos) : log2vis(pos) + 1;
1644
1645         pos_type body_pos = rit_par->beginningOfBody();
1646         if ((body_pos > 0) &&
1647             ((body_pos - 1 > last) || !rit_par->isLineSeparator(body_pos - 1)))
1648                 body_pos = 0;
1649
1650         for (pos_type vpos = rit_pos; vpos < cursor_vpos; ++vpos) {
1651                 pos_type pos = vis2log(vpos);
1652                 if (body_pos > 0 && pos == body_pos - 1) {
1653                         x += fill_label_hfill +
1654                                 font_metrics::width(
1655                                         rit_par->layout()->labelsep,
1656                                         getLabelFont(bv()->buffer(), rit_par));
1657                         if (rit_par->isLineSeparator(body_pos - 1))
1658                                 x -= singleWidth(rit_par, body_pos - 1);
1659                 }
1660
1661                 if (hfillExpansion(*this, rit, pos)) {
1662                         x += singleWidth(rit_par, pos);
1663                         if (pos >= body_pos)
1664                                 x += fill_hfill;
1665                         else
1666                                 x += fill_label_hfill;
1667                 } else if (rit_par->isSeparator(pos)) {
1668                         x += singleWidth(rit_par, pos);
1669                         if (pos >= body_pos)
1670                                 x += fill_separator;
1671                 } else
1672                         x += singleWidth(rit_par, pos);
1673         }
1674         return x;
1675 }
1676
1677
1678 void LyXText::setCursorIntern(ParagraphList::iterator pit,
1679                               pos_type pos, bool setfont, bool boundary)
1680 {
1681         UpdatableInset * it = pit->inInset();
1682         if (it) {
1683                 if (it != inset_owner) {
1684                         lyxerr[Debug::INSETS] << "InsetText   is " << it
1685                                               << endl
1686                                               << "inset_owner is "
1687                                               << inset_owner << endl;
1688 #ifdef WITH_WARNINGS
1689 #warning I believe this code is wrong. (Lgb)
1690 #warning Jürgen, have a look at this. (Lgb)
1691 #warning Hmmm, I guess you are right but we
1692 #warning should verify when this is needed
1693 #endif
1694                         // Jürgen, would you like to have a look?
1695                         // I guess we need to move the outer cursor
1696                         // and open and lock the inset (bla bla bla)
1697                         // stuff I don't know... so can you have a look?
1698                         // (Lgb)
1699                         // I moved the lyxerr stuff in here so we can see if
1700                         // this is actually really needed and where!
1701                         // (Jug)
1702                         // it->getLyXText(bv())->setCursorIntern(bv(), par, pos, setfont, boundary);
1703                         return;
1704                 }
1705         }
1706
1707         setCursor(cursor, pit, pos, boundary);
1708         if (setfont)
1709                 setCurrentFont();
1710 }
1711
1712
1713 void LyXText::setCurrentFont()
1714 {
1715         pos_type pos = cursor.pos();
1716         ParagraphList::iterator pit = cursor.par();
1717
1718         if (cursor.boundary() && pos > 0)
1719                 --pos;
1720
1721         if (pos > 0) {
1722                 if (pos == pit->size())
1723                         --pos;
1724                 else // potentional bug... BUG (Lgb)
1725                         if (pit->isSeparator(pos)) {
1726                                 if (pos > cursorRow()->pos() &&
1727                                     bidi_level(pos) % 2 ==
1728                                     bidi_level(pos - 1) % 2)
1729                                         --pos;
1730                                 else if (pos + 1 < pit->size())
1731                                         ++pos;
1732                         }
1733         }
1734
1735         current_font =
1736                 pit->getFontSettings(bv()->buffer()->params, pos);
1737         real_current_font = getFont(bv()->buffer(), pit, pos);
1738
1739         if (cursor.pos() == pit->size() &&
1740             isBoundary(bv()->buffer(), *pit, cursor.pos()) &&
1741             !cursor.boundary()) {
1742                 Language const * lang =
1743                         pit->getParLanguage(bv()->buffer()->params);
1744                 current_font.setLanguage(lang);
1745                 current_font.setNumber(LyXFont::OFF);
1746                 real_current_font.setLanguage(lang);
1747                 real_current_font.setNumber(LyXFont::OFF);
1748         }
1749 }
1750
1751
1752 // returns the column near the specified x-coordinate of the row
1753 // x is set to the real beginning of this column
1754 pos_type
1755 LyXText::getColumnNearX(RowList::iterator rit, int & x, bool & boundary) const
1756 {
1757         float tmpx = 0.0;
1758         float fill_separator;
1759         float fill_hfill;
1760         float fill_label_hfill;
1761
1762         prepareToPrint(rit, tmpx, fill_separator,
1763                        fill_hfill, fill_label_hfill);
1764
1765         pos_type vc = rit->pos();
1766         pos_type last = lastPrintablePos(*this, rit);
1767         pos_type c = 0;
1768
1769         ParagraphList::iterator rit_par = rit->par();
1770         LyXLayout_ptr const & layout = rit->par()->layout();
1771
1772         bool left_side = false;
1773
1774         pos_type body_pos = rit_par->beginningOfBody();
1775         float last_tmpx = tmpx;
1776
1777         if (body_pos > 0 &&
1778             (body_pos - 1 > last ||
1779              !rit_par->isLineSeparator(body_pos - 1)))
1780                 body_pos = 0;
1781
1782         // check for empty row
1783         if (!rit_par->size()) {
1784                 x = int(tmpx);
1785                 return 0;
1786         }
1787
1788         while (vc <= last && tmpx <= x) {
1789                 c = vis2log(vc);
1790                 last_tmpx = tmpx;
1791                 if (body_pos > 0 && c == body_pos - 1) {
1792                         tmpx += fill_label_hfill +
1793                                 font_metrics::width(layout->labelsep,
1794                                                getLabelFont(bv()->buffer(), rit_par));
1795                         if (rit_par->isLineSeparator(body_pos - 1))
1796                                 tmpx -= singleWidth(rit_par, body_pos - 1);
1797                 }
1798
1799                 if (hfillExpansion(*this, rit, c)) {
1800                         tmpx += singleWidth(rit_par, c);
1801                         if (c >= body_pos)
1802                                 tmpx += fill_hfill;
1803                         else
1804                                 tmpx += fill_label_hfill;
1805                 } else if (rit_par->isSeparator(c)) {
1806                         tmpx += singleWidth(rit_par, c);
1807                         if (c >= body_pos)
1808                                 tmpx+= fill_separator;
1809                 } else {
1810                         tmpx += singleWidth(rit_par, c);
1811                 }
1812                 ++vc;
1813         }
1814
1815         if ((tmpx + last_tmpx) / 2 > x) {
1816                 tmpx = last_tmpx;
1817                 left_side = true;
1818         }
1819
1820         if (vc > last + 1)  // This shouldn't happen.
1821                 vc = last + 1;
1822
1823         boundary = false;
1824         // This (rtl_support test) is not needed, but gives
1825         // some speedup if rtl_support=false
1826         RowList::iterator next_rit = boost::next(rit);
1827
1828         bool const lastrow = lyxrc.rtl_support &&
1829                 (next_rit == rowlist_.end() ||
1830                  next_rit->par() != rit_par);
1831
1832         // If lastrow is false, we don't need to compute
1833         // the value of rtl.
1834         bool const rtl = (lastrow)
1835                 ? rit_par->isRightToLeftPar(bv()->buffer()->params)
1836                 : false;
1837         if (lastrow &&
1838                  ((rtl &&  left_side && vc == rit->pos() && x < tmpx - 5) ||
1839                    (!rtl && !left_side && vc == last + 1   && x > tmpx + 5)))
1840                 c = last + 1;
1841         else if (vc == rit->pos()) {
1842                 c = vis2log(vc);
1843                 if (bidi_level(c) % 2 == 1)
1844                         ++c;
1845         } else {
1846                 c = vis2log(vc - 1);
1847                 bool const rtl = (bidi_level(c) % 2 == 1);
1848                 if (left_side == rtl) {
1849                         ++c;
1850                         boundary = isBoundary(bv()->buffer(), *rit_par, c);
1851                 }
1852         }
1853
1854         if (rit->pos() <= last && c > last
1855             && rit_par->isNewline(last)) {
1856                 if (bidi_level(last) % 2 == 0)
1857                         tmpx -= singleWidth(rit_par, last);
1858                 else
1859                         tmpx += singleWidth(rit_par, last);
1860                 c = last;
1861         }
1862
1863         c -= rit->pos();
1864         x = int(tmpx);
1865         return c;
1866 }
1867
1868
1869 void LyXText::setCursorFromCoordinates(int x, int y)
1870 {
1871         LyXCursor old_cursor = cursor;
1872
1873         setCursorFromCoordinates(cursor, x, y);
1874         setCurrentFont();
1875         deleteEmptyParagraphMechanism(old_cursor);
1876 }
1877
1878
1879 namespace {
1880
1881         /**
1882          * return true if the cursor given is at the end of a row,
1883          * and the next row is filled by an inset that spans an entire
1884          * row.
1885          */
1886         bool beforeFullRowInset(LyXText & lt, LyXCursor const & cur)
1887         {
1888                 RowList::iterator row = lt.getRow(cur);
1889                 if (boost::next(row) == lt.rows().end())
1890                         return false;
1891
1892                 Row const & next = *boost::next(row);
1893
1894                 if (next.pos() != cur.pos() || next.par() != cur.par())
1895                         return false;
1896
1897                 if (cur.pos() == cur.par()->size()
1898                     || !cur.par()->isInset(cur.pos()))
1899                         return false;
1900
1901                 Inset const * inset = cur.par()->getInset(cur.pos());
1902                 if (inset->needFullRow() || inset->display())
1903                         return true;
1904
1905                 return false;
1906         }
1907 }
1908
1909
1910 void LyXText::setCursorFromCoordinates(LyXCursor & cur, int x, int y)
1911 {
1912         // Get the row first.
1913
1914         RowList::iterator row = getRowNearY(y);
1915         bool bound = false;
1916         pos_type const column = getColumnNearX(row, x, bound);
1917         cur.par(row->par());
1918         cur.pos(row->pos() + column);
1919         cur.x(x);
1920         cur.y(y + row->baseline());
1921
1922         if (beforeFullRowInset(*this, cur)) {
1923                 pos_type const last = lastPrintablePos(*this, row);
1924                 RowList::iterator next_row = boost::next(row);
1925
1926                 float x = getCursorX(next_row, cur.pos(), last, bound);
1927                 cur.ix(int(x));
1928                 cur.iy(y + row->height() + next_row->baseline());
1929         } else {
1930                 cur.iy(cur.y());
1931                 cur.ix(cur.x());
1932         }
1933         cur.boundary(bound);
1934 }
1935
1936
1937 void LyXText::cursorLeft(bool internal)
1938 {
1939         if (cursor.pos() > 0) {
1940                 bool boundary = cursor.boundary();
1941                 setCursor(cursor.par(), cursor.pos() - 1, true, false);
1942                 if (!internal && !boundary &&
1943                     isBoundary(bv()->buffer(), *cursor.par(), cursor.pos() + 1))
1944                         setCursor(cursor.par(), cursor.pos() + 1, true, true);
1945         } else if (cursor.par() != ownerParagraphs().begin()) { // steps into the above paragraph.
1946                 ParagraphList::iterator pit = boost::prior(cursor.par());
1947                 setCursor(pit, pit->size());
1948         }
1949 }
1950
1951
1952 void LyXText::cursorRight(bool internal)
1953 {
1954         bool const at_end = (cursor.pos() == cursor.par()->size());
1955         bool const at_newline = !at_end &&
1956                 cursor.par()->isNewline(cursor.pos());
1957
1958         if (!internal && cursor.boundary() && !at_newline)
1959                 setCursor(cursor.par(), cursor.pos(), true, false);
1960         else if (!at_end) {
1961                 setCursor(cursor.par(), cursor.pos() + 1, true, false);
1962                 if (!internal &&
1963                     isBoundary(bv()->buffer(), *cursor.par(), cursor.pos()))
1964                         setCursor(cursor.par(), cursor.pos(), true, true);
1965         } else if (boost::next(cursor.par()) != ownerParagraphs().end())
1966                 setCursor(boost::next(cursor.par()), 0);
1967 }
1968
1969
1970 void LyXText::cursorUp(bool selecting)
1971 {
1972 #if 1
1973         int x = cursor.x_fix();
1974         int y = cursor.y() - cursorRow()->baseline() - 1;
1975         setCursorFromCoordinates(x, y);
1976         if (!selecting) {
1977                 int topy = top_y();
1978                 int y1 = cursor.iy() - topy;
1979                 int y2 = y1;
1980                 y -= topy;
1981                 Inset * inset_hit = checkInsetHit(x, y1);
1982                 if (inset_hit && isHighlyEditableInset(inset_hit)) {
1983                         inset_hit->localDispatch(
1984                                 FuncRequest(bv(), LFUN_INSET_EDIT, x, y - (y2 - y1), mouse_button::none));
1985                 }
1986         }
1987 #else
1988         setCursorFromCoordinates(bv(), cursor.x_fix(),
1989                                  cursor.y() - cursorRow()->baseline() - 1);
1990 #endif
1991 }
1992
1993
1994 void LyXText::cursorDown(bool selecting)
1995 {
1996 #if 1
1997         int x = cursor.x_fix();
1998         int y = cursor.y() - cursorRow()->baseline() + cursorRow()->height() + 1;
1999         setCursorFromCoordinates(x, y);
2000         if (!selecting && cursorRow() == cursorIRow()) {
2001                 int topy = top_y();
2002                 int y1 = cursor.iy() - topy;
2003                 int y2 = y1;
2004                 y -= topy;
2005                 Inset * inset_hit = checkInsetHit(x, y1);
2006                 if (inset_hit && isHighlyEditableInset(inset_hit)) {
2007                         FuncRequest cmd(bv(), LFUN_INSET_EDIT, x, y - (y2 - y1), mouse_button::none);
2008                         inset_hit->localDispatch(cmd);
2009                 }
2010         }
2011 #else
2012         setCursorFromCoordinates(bv(), cursor.x_fix(),
2013                                  cursor.y() - cursorRow()->baseline()
2014                                  + cursorRow()->height() + 1);
2015 #endif
2016 }
2017
2018
2019 void LyXText::cursorUpParagraph()
2020 {
2021         if (cursor.pos() > 0) {
2022                 setCursor(cursor.par(), 0);
2023         }
2024         else if (cursor.par() != ownerParagraphs().begin()) {
2025                 setCursor(boost::prior(cursor.par()), 0);
2026         }
2027 }
2028
2029
2030 void LyXText::cursorDownParagraph()
2031 {
2032         ParagraphList::iterator par = cursor.par();
2033         ParagraphList::iterator next_par = boost::next(par);
2034
2035         if (next_par != ownerParagraphs().end()) {
2036                 setCursor(next_par, 0);
2037         } else {
2038                 setCursor(par, par->size());
2039         }
2040 }
2041
2042 // fix the cursor `cur' after a characters has been deleted at `where'
2043 // position. Called by deleteEmptyParagraphMechanism
2044 void LyXText::fixCursorAfterDelete(LyXCursor & cur,
2045                                    LyXCursor const & where)
2046 {
2047         // if cursor is not in the paragraph where the delete occured,
2048         // do nothing
2049         if (cur.par() != where.par())
2050                 return;
2051
2052         // if cursor position is after the place where the delete occured,
2053         // update it
2054         if (cur.pos() > where.pos())
2055                 cur.pos(cur.pos()-1);
2056
2057         // check also if we don't want to set the cursor on a spot behind the
2058         // pagragraph because we erased the last character.
2059         if (cur.pos() > cur.par()->size())
2060                 cur.pos(cur.par()->size());
2061
2062         // recompute row et al. for this cursor
2063         setCursor(cur, cur.par(), cur.pos(), cur.boundary());
2064 }
2065
2066
2067 bool LyXText::deleteEmptyParagraphMechanism(LyXCursor const & old_cursor)
2068 {
2069         // Would be wrong to delete anything if we have a selection.
2070         if (selection.set())
2071                 return false;
2072
2073         // We allow all kinds of "mumbo-jumbo" when freespacing.
2074         if (old_cursor.par()->layout()->free_spacing
2075             || old_cursor.par()->isFreeSpacing()) {
2076                 return false;
2077         }
2078
2079         /* Ok I'll put some comments here about what is missing.
2080            I have fixed BackSpace (and thus Delete) to not delete
2081            double-spaces automagically. I have also changed Cut,
2082            Copy and Paste to hopefully do some sensible things.
2083            There are still some small problems that can lead to
2084            double spaces stored in the document file or space at
2085            the beginning of paragraphs. This happens if you have
2086            the cursor betwenn to spaces and then save. Or if you
2087            cut and paste and the selection have a space at the
2088            beginning and then save right after the paste. I am
2089            sure none of these are very hard to fix, but I will
2090            put out 1.1.4pre2 with FIX_DOUBLE_SPACE defined so
2091            that I can get some feedback. (Lgb)
2092         */
2093
2094         // If old_cursor.pos() == 0 and old_cursor.pos()(1) == LineSeparator
2095         // delete the LineSeparator.
2096         // MISSING
2097
2098         // If old_cursor.pos() == 1 and old_cursor.pos()(0) == LineSeparator
2099         // delete the LineSeparator.
2100         // MISSING
2101
2102         // If the pos around the old_cursor were spaces, delete one of them.
2103         if (old_cursor.par() != cursor.par()
2104             || old_cursor.pos() != cursor.pos()) {
2105                 // Only if the cursor has really moved
2106
2107                 if (old_cursor.pos() > 0
2108                     && old_cursor.pos() < old_cursor.par()->size()
2109                     && old_cursor.par()->isLineSeparator(old_cursor.pos())
2110                     && old_cursor.par()->isLineSeparator(old_cursor.pos() - 1)) {
2111                         old_cursor.par()->erase(old_cursor.pos() - 1);
2112                         redoParagraphs(old_cursor, boost::next(old_cursor.par()));
2113
2114 #ifdef WITH_WARNINGS
2115 #warning This will not work anymore when we have multiple views of the same buffer
2116 // In this case, we will have to correct also the cursors held by
2117 // other bufferviews. It will probably be easier to do that in a more
2118 // automated way in LyXCursor code. (JMarc 26/09/2001)
2119 #endif
2120                         // correct all cursors held by the LyXText
2121                         fixCursorAfterDelete(cursor, old_cursor);
2122                         fixCursorAfterDelete(selection.cursor,
2123                                              old_cursor);
2124                         fixCursorAfterDelete(selection.start,
2125                                              old_cursor);
2126                         fixCursorAfterDelete(selection.end, old_cursor);
2127                         fixCursorAfterDelete(last_sel_cursor,
2128                                              old_cursor);
2129                         fixCursorAfterDelete(toggle_cursor, old_cursor);
2130                         fixCursorAfterDelete(toggle_end_cursor,
2131                                              old_cursor);
2132                         return false;
2133                 }
2134         }
2135
2136         // don't delete anything if this is the ONLY paragraph!
2137         if (ownerParagraphs().size() == 1)
2138                 return false;
2139
2140         // Do not delete empty paragraphs with keepempty set.
2141         if (old_cursor.par()->allowEmpty())
2142                 return false;
2143
2144         // only do our magic if we changed paragraph
2145         if (old_cursor.par() == cursor.par())
2146                 return false;
2147
2148         // record if we have deleted a paragraph
2149         // we can't possibly have deleted a paragraph before this point
2150         bool deleted = false;
2151
2152         if (old_cursor.par()->empty() ||
2153             (old_cursor.par()->size() == 1 &&
2154              old_cursor.par()->isLineSeparator(0))) {
2155                 // ok, we will delete anything
2156                 LyXCursor tmpcursor;
2157
2158                 deleted = true;
2159
2160                 bool selection_position_was_oldcursor_position = (
2161                         selection.cursor.par()  == old_cursor.par()
2162                         && selection.cursor.pos() == old_cursor.pos());
2163
2164                 if (getRow(old_cursor) != rows().begin()) {
2165                         RowList::iterator prevrow = boost::prior(getRow(old_cursor));
2166                         postPaint();
2167                         tmpcursor = cursor;
2168                         cursor = old_cursor; // that undo can restore the right cursor position
2169                         #warning FIXME. --end() iterator is usable here
2170                         ParagraphList::iterator endpit = boost::next(old_cursor.par());
2171                         while (endpit != ownerParagraphs().end() &&
2172                                endpit->getDepth()) {
2173                                 ++endpit;
2174                         }
2175
2176                         setUndo(bv(), Undo::DELETE, old_cursor.par(),
2177                                 boost::prior(endpit));
2178                         cursor = tmpcursor;
2179
2180                         // delete old row
2181                         removeRow(getRow(old_cursor));
2182                         // delete old par
2183                         ownerParagraphs().erase(old_cursor.par());
2184
2185                         /* Breakagain the next par. Needed because of
2186                          * the parindent that can occur or dissappear.
2187                          * The next row can change its height, if
2188                          * there is another layout before */
2189                         RowList::iterator tmprit = boost::next(prevrow);
2190                         if (tmprit != rows().end()) {
2191                                 breakAgain(tmprit);
2192                                 updateCounters();
2193                         }
2194                         setHeightOfRow(prevrow);
2195                 } else {
2196                         RowList::iterator nextrow = boost::next(getRow(old_cursor));
2197                         postPaint();
2198
2199                         tmpcursor = cursor;
2200                         cursor = old_cursor; // that undo can restore the right cursor position
2201 #warning FIXME. --end() iterator is usable here
2202                         ParagraphList::iterator endpit = boost::next(old_cursor.par());
2203                         while (endpit != ownerParagraphs().end() &&
2204                                endpit->getDepth()) {
2205                                 ++endpit;
2206                         }
2207
2208                         setUndo(bv(), Undo::DELETE, old_cursor.par(), boost::prior(endpit));
2209                         cursor = tmpcursor;
2210
2211                         // delete old row
2212                         removeRow(getRow(old_cursor));
2213                         // delete old par
2214                         ownerParagraphs().erase(old_cursor.par());
2215
2216                         /* Breakagain the next par. Needed because of
2217                            the parindent that can occur or dissappear.
2218                            The next row can change its height, if
2219                            there is another layout before */
2220                         if (nextrow != rows().end()) {
2221                                 breakAgain(nextrow);
2222                                 updateCounters();
2223                         }
2224                 }
2225
2226                 // correct cursor y
2227                 setCursorIntern(cursor.par(), cursor.pos());
2228
2229                 if (selection_position_was_oldcursor_position) {
2230                         // correct selection
2231                         selection.cursor = cursor;
2232                 }
2233         }
2234         if (!deleted) {
2235                 if (old_cursor.par()->stripLeadingSpaces()) {
2236                         redoParagraphs(old_cursor, boost::next(old_cursor.par()));
2237                         // correct cursor y
2238                         setCursorIntern(cursor.par(), cursor.pos());
2239                         selection.cursor = cursor;
2240                 }
2241         }
2242         return deleted;
2243 }
2244
2245
2246 ParagraphList & LyXText::ownerParagraphs() const
2247 {
2248         if (inset_owner) {
2249                 return inset_owner->paragraphs;
2250         }
2251         return bv_owner->buffer()->paragraphs;
2252 }
2253
2254
2255 bool LyXText::needRefresh() const
2256 {
2257         return need_refresh_;
2258 }
2259
2260
2261 void LyXText::clearPaint()
2262 {
2263         need_refresh_ = false;
2264 }
2265
2266
2267 void LyXText::postPaint()
2268 {
2269         need_refresh_ = true;
2270
2271         // We are an inset's lyxtext. Tell the top-level lyxtext
2272         // it needs to update the row we're in.
2273         if (inset_owner)
2274                 bv()->text->postPaint();
2275 }
2276
2277
2278 bool LyXText::isInInset() const
2279 {
2280         // Sub-level has non-null bv owner and
2281         // non-null inset owner.
2282         return inset_owner != 0 && bv_owner != 0;
2283 }
2284
2285
2286 int defaultRowHeight()
2287 {
2288         LyXFont const font(LyXFont::ALL_SANE);
2289         return int(font_metrics::maxAscent(font)
2290                  + font_metrics::maxDescent(font) * 1.5);
2291 }