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