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