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