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