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