]> git.lyx.org Git - lyx.git/blob - src/text2.C
143151d4eacfd04e440ac4ee8cd56d9b099fba8a
[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 "bufferlist.h"
27 #include "bufferparams.h"
28 #include "BufferView.h"
29 #include "Bullet.h"
30 #include "coordcache.h"
31 #include "cursor.h"
32 #include "CutAndPaste.h"
33 #include "debug.h"
34 #include "dispatchresult.h"
35 #include "errorlist.h"
36 #include "funcrequest.h"
37 #include "gettext.h"
38 #include "language.h"
39 #include "LColor.h"
40 #include "lyxfunc.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 "pariterator.h"
48 #include "lyxserver.h"
49 #include "lyxsocket.h"
50 #include "undo.h"
51 #include "vspace.h"
52
53 #include "frontends/FontMetrics.h"
54
55 #include "insets/insetenv.h"
56
57 #include "mathed/InsetMathHull.h"
58
59 #include "support/textutils.h"
60
61 #include <boost/current_function.hpp>
62
63 #include <sstream>
64
65 using lyx::CoordCache;
66 using lyx::docstring;
67 using lyx::pit_type;
68 using lyx::pos_type;
69
70 using std::endl;
71 using std::ostringstream;
72 using std::string;
73 using std::max;
74 using std::min;
75
76
77 LyXText::LyXText(BufferView * bv)
78         : maxwidth_(bv ? bv->workWidth() : 100),
79           current_font(LyXFont::ALL_INHERIT),
80           background_color_(LColor::background),
81           bv_owner(bv),
82           autoBreakRows_(false)
83 {}
84
85
86 void LyXText::init(BufferView * bv)
87 {
88         BOOST_ASSERT(bv);
89         bv_owner = bv;
90         maxwidth_ = bv->workWidth();
91         dim_.wid = maxwidth_;
92         dim_.asc = 10;
93         dim_.des = 10;
94
95         pit_type const end = paragraphs().size();
96         for (pit_type pit = 0; pit != end; ++pit)
97                 pars_[pit].rows().clear();
98
99         updateLabels(*bv->buffer());
100 }
101
102
103 bool LyXText::isMainText() const
104 {
105         return &bv()->buffer()->text() == this;
106 }
107
108
109 //takes screen x,y coordinates
110 InsetBase * LyXText::checkInsetHit(int x, int y) const
111 {
112         pit_type pit = getPitNearY(y);
113         BOOST_ASSERT(pit != -1);
114
115         Paragraph const & par = pars_[pit];
116
117         lyxerr[Debug::DEBUG]
118                 << BOOST_CURRENT_FUNCTION
119                 << ": x: " << x
120                 << " y: " << y
121                 << "  pit: " << pit
122                 << endl;
123         InsetList::const_iterator iit = par.insetlist.begin();
124         InsetList::const_iterator iend = par.insetlist.end();
125         for (; iit != iend; ++iit) {
126                 InsetBase * inset = iit->inset;
127 #if 1
128                 lyxerr[Debug::DEBUG]
129                         << BOOST_CURRENT_FUNCTION
130                         << ": examining inset " << inset << endl;
131
132                 if (bv()->coordCache().getInsets().has(inset))
133                         lyxerr[Debug::DEBUG]
134                                 << BOOST_CURRENT_FUNCTION
135                                 << ": xo: " << inset->xo(*bv()) << "..."
136                                 << inset->xo(*bv()) + inset->width()
137                                 << " yo: " << inset->yo(*bv()) - inset->ascent()
138                                 << "..."
139                                 << inset->yo(*bv()) + inset->descent()
140                                 << endl;
141                 else
142                         lyxerr[Debug::DEBUG]
143                                 << BOOST_CURRENT_FUNCTION
144                                 << ": inset has no cached position" << endl;
145 #endif
146                 if (inset->covers(*bv(), x, y)) {
147                         lyxerr[Debug::DEBUG]
148                                 << BOOST_CURRENT_FUNCTION
149                                 << ": Hit inset: " << inset << endl;
150                         return inset;
151                 }
152         }
153         lyxerr[Debug::DEBUG]
154                 << BOOST_CURRENT_FUNCTION
155                 << ": No inset hit. " << endl;
156         return 0;
157 }
158
159
160
161 // Gets the fully instantiated font at a given position in a paragraph
162 // Basically the same routine as Paragraph::getFont() in paragraph.C.
163 // The difference is that this one is used for displaying, and thus we
164 // are allowed to make cosmetic improvements. For instance make footnotes
165 // smaller. (Asger)
166 LyXFont LyXText::getFont(Paragraph const & par, pos_type const pos) const
167 {
168         BOOST_ASSERT(pos >= 0);
169
170         LyXLayout_ptr const & layout = par.layout();
171 #ifdef WITH_WARNINGS
172 #warning broken?
173 #endif
174         BufferParams const & params = bv()->buffer()->params();
175         pos_type const body_pos = par.beginOfBody();
176
177         // We specialize the 95% common case:
178         if (!par.getDepth()) {
179                 LyXFont f = par.getFontSettings(params, pos);
180                 if (!isMainText())
181                         applyOuterFont(f);
182                 LyXFont lf;
183                 LyXFont rlf;
184                 if (layout->labeltype == LABEL_MANUAL && pos < body_pos) {
185                         lf = layout->labelfont;
186                         rlf = layout->reslabelfont;
187                 } else {
188                         lf = layout->font;
189                         rlf = layout->resfont;
190                 }
191                 // In case the default family has been customized
192                 if (lf.family() == LyXFont::INHERIT_FAMILY)
193                         rlf.setFamily(params.getFont().family());
194                 return f.realize(rlf);
195         }
196
197         // The uncommon case need not be optimized as much
198         LyXFont layoutfont;
199         if (pos < body_pos)
200                 layoutfont = layout->labelfont;
201         else
202                 layoutfont = layout->font;
203
204         LyXFont font = par.getFontSettings(params, pos);
205         font.realize(layoutfont);
206
207         if (!isMainText())
208                 applyOuterFont(font);
209
210         // Find the pit value belonging to paragraph. This will not break
211         // even if pars_ would not be a vector anymore.
212         // Performance appears acceptable.
213
214         pit_type pit = pars_.size();
215         for (pit_type it = 0; it < pit; ++it)
216                 if (&pars_[it] == &par) {
217                         pit = it;
218                         break;
219                 }
220         // Realize against environment font information
221         // NOTE: the cast to pit_type should be removed when pit_type
222         // changes to a unsigned integer.
223         if (pit < pit_type(pars_.size()))
224                 font.realize(outerFont(pit, pars_));
225
226         // Realize with the fonts of lesser depth.
227         font.realize(params.getFont());
228
229         return font;
230 }
231
232 // There are currently two font mechanisms in LyX:
233 // 1. The font attributes in a lyxtext, and
234 // 2. The inset-specific font properties, defined in an inset's
235 // metrics() and draw() methods and handed down the inset chain through
236 // the pi/mi parameters, and stored locally in a lyxtext in font_.
237 // This is where the two are integrated in the final fully realized
238 // font.
239 void LyXText::applyOuterFont(LyXFont & font) const {
240         LyXFont lf(font_);
241         lf.reduce(bv()->buffer()->params().getFont());
242         lf.realize(font);
243         lf.setLanguage(font.language());
244         font = lf;
245 }
246
247
248 LyXFont LyXText::getLayoutFont(pit_type const pit) const
249 {
250         LyXLayout_ptr const & layout = pars_[pit].layout();
251
252         if (!pars_[pit].getDepth())  {
253                 LyXFont lf = layout->resfont;
254                 // In case the default family has been customized
255                 if (layout->font.family() == LyXFont::INHERIT_FAMILY)
256                         lf.setFamily(bv()->buffer()->params().getFont().family());
257                 return lf;
258         }
259
260         LyXFont font = layout->font;
261         // Realize with the fonts of lesser depth.
262         //font.realize(outerFont(pit, paragraphs()));
263         font.realize(bv()->buffer()->params().getFont());
264
265         return font;
266 }
267
268
269 LyXFont LyXText::getLabelFont(Paragraph const & par) const
270 {
271         LyXLayout_ptr const & layout = par.layout();
272
273         if (!par.getDepth()) {
274                 LyXFont lf = layout->reslabelfont;
275                 // In case the default family has been customized
276                 if (layout->labelfont.family() == LyXFont::INHERIT_FAMILY)
277                         lf.setFamily(bv()->buffer()->params().getFont().family());
278                 return lf;
279         }
280
281         LyXFont font = layout->labelfont;
282         // Realize with the fonts of lesser depth.
283         font.realize(bv()->buffer()->params().getFont());
284
285         return font;
286 }
287
288
289 void LyXText::setCharFont(pit_type pit, pos_type pos, LyXFont const & fnt)
290 {
291         LyXFont font = fnt;
292         LyXLayout_ptr const & layout = pars_[pit].layout();
293
294         // Get concrete layout font to reduce against
295         LyXFont layoutfont;
296
297         if (pos < pars_[pit].beginOfBody())
298                 layoutfont = layout->labelfont;
299         else
300                 layoutfont = layout->font;
301
302         // Realize against environment font information
303         if (pars_[pit].getDepth()) {
304                 pit_type tp = pit;
305                 while (!layoutfont.resolved() &&
306                        tp != pit_type(paragraphs().size()) &&
307                        pars_[tp].getDepth()) {
308                         tp = outerHook(tp, paragraphs());
309                         if (tp != pit_type(paragraphs().size()))
310                                 layoutfont.realize(pars_[tp].layout()->font);
311                 }
312         }
313
314         // Inside inset, apply the inset's font attributes if any
315         // (charstyle!)
316         if (!isMainText())
317                 layoutfont.realize(font_);
318
319         layoutfont.realize(bv()->buffer()->params().getFont());
320
321         // Now, reduce font against full layout font
322         font.reduce(layoutfont);
323
324         pars_[pit].setFont(pos, font);
325 }
326
327
328 // return past-the-last paragraph influenced by a layout change on pit
329 pit_type LyXText::undoSpan(pit_type pit)
330 {
331         pit_type end = paragraphs().size();
332         pit_type nextpit = pit + 1;
333         if (nextpit == end)
334                 return nextpit;
335         //because of parindents
336         if (!pars_[pit].getDepth())
337                 return boost::next(nextpit);
338         //because of depth constrains
339         for (; nextpit != end; ++pit, ++nextpit) {
340                 if (!pars_[pit].getDepth())
341                         break;
342         }
343         return nextpit;
344 }
345
346
347 void LyXText::setLayout(pit_type start, pit_type end, string const & layout)
348 {
349         BOOST_ASSERT(start != end);
350
351         BufferParams const & bufparams = bv()->buffer()->params();
352         LyXLayout_ptr const & lyxlayout = bufparams.getLyXTextClass()[layout];
353
354         for (pit_type pit = start; pit != end; ++pit) {
355                 pars_[pit].applyLayout(lyxlayout);
356                 if (lyxlayout->margintype == MARGIN_MANUAL)
357                         pars_[pit].setLabelWidthString(lyxlayout->labelstring());
358         }
359 }
360
361
362 // set layout over selection and make a total rebreak of those paragraphs
363 void LyXText::setLayout(LCursor & cur, string const & layout)
364 {
365         BOOST_ASSERT(this == cur.text());
366         // special handling of new environment insets
367         BufferView & bv = cur.bv();
368         BufferParams const & params = bv.buffer()->params();
369         LyXLayout_ptr const & lyxlayout = params.getLyXTextClass()[layout];
370         if (lyxlayout->is_environment) {
371                 // move everything in a new environment inset
372                 lyxerr[Debug::DEBUG] << "setting layout " << layout << endl;
373                 lyx::dispatch(FuncRequest(LFUN_LINE_BEGIN));
374                 lyx::dispatch(FuncRequest(LFUN_LINE_END_SELECT));
375                 lyx::dispatch(FuncRequest(LFUN_CUT));
376                 InsetBase * inset = new InsetEnvironment(params, layout);
377                 insertInset(cur, inset);
378                 //inset->edit(cur, true);
379                 //lyx::dispatch(FuncRequest(LFUN_PASTE));
380                 return;
381         }
382
383         pit_type start = cur.selBegin().pit();
384         pit_type end = cur.selEnd().pit() + 1;
385         pit_type undopit = undoSpan(end - 1);
386         recUndo(start, undopit - 1);
387         setLayout(start, end, layout);
388         updateLabels(cur.buffer());
389 }
390
391
392 namespace {
393
394
395 bool changeDepthAllowed(LyXText::DEPTH_CHANGE type,
396                         Paragraph const & par, int max_depth)
397 {
398         if (par.layout()->labeltype == LABEL_BIBLIO)
399                 return false;
400         int const depth = par.params().depth();
401         if (type == LyXText::INC_DEPTH && depth < max_depth)
402                 return true;
403         if (type == LyXText::DEC_DEPTH && depth > 0)
404                 return true;
405         return false;
406 }
407
408
409 }
410
411
412 bool LyXText::changeDepthAllowed(LCursor & cur, DEPTH_CHANGE type) const
413 {
414         BOOST_ASSERT(this == cur.text());
415         // this happens when selecting several cells in tabular (bug 2630)
416         if (cur.selBegin().idx() != cur.selEnd().idx())
417                 return false;
418
419         pit_type const beg = cur.selBegin().pit();
420         pit_type const end = cur.selEnd().pit() + 1;
421         int max_depth = (beg != 0 ? pars_[beg - 1].getMaxDepthAfter() : 0);
422
423         for (pit_type pit = beg; pit != end; ++pit) {
424                 if (::changeDepthAllowed(type, pars_[pit], max_depth))
425                         return true;
426                 max_depth = pars_[pit].getMaxDepthAfter();
427         }
428         return false;
429 }
430
431
432 void LyXText::changeDepth(LCursor & cur, DEPTH_CHANGE type)
433 {
434         BOOST_ASSERT(this == cur.text());
435         pit_type const beg = cur.selBegin().pit();
436         pit_type const end = cur.selEnd().pit() + 1;
437         recordUndoSelection(cur);
438         int max_depth = (beg != 0 ? pars_[beg - 1].getMaxDepthAfter() : 0);
439
440         for (pit_type pit = beg; pit != end; ++pit) {
441                 Paragraph & par = pars_[pit];
442                 if (::changeDepthAllowed(type, par, max_depth)) {
443                         int const depth = par.params().depth();
444                         if (type == INC_DEPTH)
445                                 par.params().depth(depth + 1);
446                         else
447                                 par.params().depth(depth - 1);
448                 }
449                 max_depth = par.getMaxDepthAfter();
450         }
451         // this handles the counter labels, and also fixes up
452         // depth values for follow-on (child) paragraphs
453         updateLabels(cur.buffer());
454 }
455
456
457 // set font over selection
458 void LyXText::setFont(LCursor & cur, LyXFont const & font, bool toggleall)
459 {
460         BOOST_ASSERT(this == cur.text());
461         // if there is no selection just set the current_font
462         if (!cur.selection()) {
463                 // Determine basis font
464                 LyXFont layoutfont;
465                 pit_type pit = cur.pit();
466                 if (cur.pos() < pars_[pit].beginOfBody())
467                         layoutfont = getLabelFont(pars_[pit]);
468                 else
469                         layoutfont = getLayoutFont(pit);
470
471                 // Update current font
472                 real_current_font.update(font,
473                                          cur.buffer().params().language,
474                                          toggleall);
475
476                 // Reduce to implicit settings
477                 current_font = real_current_font;
478                 current_font.reduce(layoutfont);
479                 // And resolve it completely
480                 real_current_font.realize(layoutfont);
481
482                 return;
483         }
484
485         // Ok, we have a selection.
486         recordUndoSelection(cur);
487
488         DocIterator dit = cur.selectionBegin();
489         DocIterator ditend = cur.selectionEnd();
490
491         BufferParams const & params = cur.buffer().params();
492
493         // Don't use forwardChar here as ditend might have
494         // pos() == lastpos() and forwardChar would miss it.
495         // Can't use forwardPos either as this descends into
496         // nested insets.
497         for (; dit != ditend; dit.forwardPosNoDescend()) {
498                 if (dit.pos() != dit.lastpos()) {
499                         LyXFont f = getFont(dit.paragraph(), dit.pos());
500                         f.update(font, params.language, toggleall);
501                         setCharFont(dit.pit(), dit.pos(), f);
502                 }
503         }
504 }
505
506
507 // the cursor set functions have a special mechanism. When they
508 // realize you left an empty paragraph, they will delete it.
509
510 bool LyXText::cursorHome(LCursor & cur)
511 {
512         BOOST_ASSERT(this == cur.text());
513         Row const & row = cur.paragraph().getRow(cur.pos(),cur.boundary());
514
515         return setCursor(cur, cur.pit(), row.pos());
516 }
517
518
519 bool LyXText::cursorEnd(LCursor & cur)
520 {
521         BOOST_ASSERT(this == cur.text());
522         // if not on the last row of the par, put the cursor before
523         // the final space exept if I have a spanning inset or one string
524         // is so long that we force a break.
525         pos_type end = cur.textRow().endpos();
526         if (end == 0)
527                 // empty text, end-1 is no valid position
528                 return false;
529         bool boundary = false;
530         if (end != cur.lastpos()) {
531                 if (!cur.paragraph().isLineSeparator(end-1)
532                     && !cur.paragraph().isNewline(end-1))
533                         boundary = true;
534                 else
535                         --end;
536         }
537         return setCursor(cur, cur.pit(), end, true, boundary);
538 }
539
540
541 bool LyXText::cursorTop(LCursor & cur)
542 {
543         BOOST_ASSERT(this == cur.text());
544         return setCursor(cur, 0, 0);
545 }
546
547
548 bool LyXText::cursorBottom(LCursor & cur)
549 {
550         BOOST_ASSERT(this == cur.text());
551         return setCursor(cur, cur.lastpit(), boost::prior(paragraphs().end())->size());
552 }
553
554
555 void LyXText::toggleFree(LCursor & cur, LyXFont const & font, bool toggleall)
556 {
557         BOOST_ASSERT(this == cur.text());
558         // If the mask is completely neutral, tell user
559         if (font == LyXFont(LyXFont::ALL_IGNORE)) {
560                 // Could only happen with user style
561                 cur.message(_("No font change defined. "
562                                            "Use Character under the Layout menu to define font change."));
563                 return;
564         }
565
566         // Try implicit word selection
567         // If there is a change in the language the implicit word selection
568         // is disabled.
569         CursorSlice resetCursor = cur.top();
570         bool implicitSelection =
571                 font.language() == ignore_language
572                 && font.number() == LyXFont::IGNORE
573                 && selectWordWhenUnderCursor(cur, lyx::WHOLE_WORD_STRICT);
574
575         // Set font
576         setFont(cur, font, toggleall);
577
578         // Implicit selections are cleared afterwards
579         // and cursor is set to the original position.
580         if (implicitSelection) {
581                 cur.clearSelection();
582                 cur.top() = resetCursor;
583                 cur.resetAnchor();
584         }
585 }
586
587
588 string LyXText::getStringToIndex(LCursor const & cur)
589 {
590         BOOST_ASSERT(this == cur.text());
591
592         docstring idxstring;
593         if (cur.selection())
594                 idxstring = cur.selectionAsString(false);
595         else {
596                 // Try implicit word selection. If there is a change
597                 // in the language the implicit word selection is
598                 // disabled.
599                 LCursor tmpcur = cur;
600                 selectWord(tmpcur, lyx::PREVIOUS_WORD);
601
602                 if (!tmpcur.selection())
603                         cur.message(_("Nothing to index!"));
604                 else if (tmpcur.selBegin().pit() != tmpcur.selEnd().pit())
605                         cur.message(_("Cannot index more than one paragraph!"));
606                 else
607                         idxstring = tmpcur.selectionAsString(false);
608         }
609
610         return lyx::to_utf8(idxstring);
611 }
612
613
614 void LyXText::setParagraph(LCursor & cur,
615                            Spacing const & spacing, LyXAlignment align,
616                            string const & labelwidthstring, bool noindent)
617 {
618         BOOST_ASSERT(cur.text());
619         // make sure that the depth behind the selection are restored, too
620         pit_type undopit = undoSpan(cur.selEnd().pit());
621         recUndo(cur.selBegin().pit(), undopit - 1);
622
623         for (pit_type pit = cur.selBegin().pit(), end = cur.selEnd().pit();
624              pit <= end; ++pit) {
625                 Paragraph & par = pars_[pit];
626                 ParagraphParameters & params = par.params();
627                 params.spacing(spacing);
628
629                 // does the layout allow the new alignment?
630                 LyXLayout_ptr const & layout = par.layout();
631
632                 if (align == LYX_ALIGN_LAYOUT)
633                         align = layout->align;
634                 if (align & layout->alignpossible) {
635                         if (align == layout->align)
636                                 params.align(LYX_ALIGN_LAYOUT);
637                         else
638                                 params.align(align);
639                 }
640                 par.setLabelWidthString(labelwidthstring);
641                 params.noindent(noindent);
642         }
643 }
644
645
646 // this really should just insert the inset and not move the cursor.
647 void LyXText::insertInset(LCursor & cur, InsetBase * inset)
648 {
649         BOOST_ASSERT(this == cur.text());
650         BOOST_ASSERT(inset);
651         cur.paragraph().insertInset(cur.pos(), inset, 
652                                     Change(cur.buffer().params().trackChanges ?
653                                            Change::INSERTED : Change::UNCHANGED));
654 }
655
656
657 // needed to insert the selection
658 void LyXText::insertStringAsLines(LCursor & cur, docstring const & str)
659 {
660         cur.buffer().insertStringAsLines(pars_, cur.pit(), cur.pos(),
661                                          current_font, str, autoBreakRows_);
662 }
663
664
665 // turn double CR to single CR, others are converted into one
666 // blank. Then insertStringAsLines is called
667 void LyXText::insertStringAsParagraphs(LCursor & cur, docstring const & str)
668 {
669         docstring linestr = str;
670         bool newline_inserted = false;
671
672         for (string::size_type i = 0, siz = linestr.size(); i < siz; ++i) {
673                 if (linestr[i] == '\n') {
674                         if (newline_inserted) {
675                                 // we know that \r will be ignored by
676                                 // insertStringAsLines. Of course, it is a dirty
677                                 // trick, but it works...
678                                 linestr[i - 1] = '\r';
679                                 linestr[i] = '\n';
680                         } else {
681                                 linestr[i] = ' ';
682                                 newline_inserted = true;
683                         }
684                 } else if (isPrintable(linestr[i])) {
685                         newline_inserted = false;
686                 }
687         }
688         insertStringAsLines(cur, linestr);
689 }
690
691
692 bool LyXText::setCursor(LCursor & cur, pit_type par, pos_type pos,
693                         bool setfont, bool boundary)
694 {
695         LCursor old = cur;
696         setCursorIntern(cur, par, pos, setfont, boundary);
697         return deleteEmptyParagraphMechanism(cur, old);
698 }
699
700
701 void LyXText::setCursor(CursorSlice & cur, pit_type par, pos_type pos)
702 {
703         BOOST_ASSERT(par != int(paragraphs().size()));
704         cur.pit() = par;
705         cur.pos() = pos;
706
707         // now some strict checking
708         Paragraph & para = getPar(par);
709
710         // None of these should happen, but we're scaredy-cats
711         if (pos < 0) {
712                 lyxerr << "dont like -1" << endl;
713                 BOOST_ASSERT(false);
714         }
715
716         if (pos > para.size()) {
717                 lyxerr << "dont like 1, pos: " << pos
718                        << " size: " << para.size()
719                        << " par: " << par << endl;
720                 BOOST_ASSERT(false);
721         }
722 }
723
724
725 void LyXText::setCursorIntern(LCursor & cur,
726                               pit_type par, pos_type pos, bool setfont, bool boundary)
727 {
728         BOOST_ASSERT(this == cur.text());
729         cur.boundary(boundary);
730         setCursor(cur.top(), par, pos);
731         cur.setTargetX();
732         if (setfont)
733                 setCurrentFont(cur);
734 }
735
736
737 void LyXText::setCurrentFont(LCursor & cur)
738 {
739         BOOST_ASSERT(this == cur.text());
740         pos_type pos = cur.pos();
741         Paragraph & par = cur.paragraph();
742
743         if (cur.boundary() && pos > 0)
744                 --pos;
745
746         if (pos > 0) {
747                 if (pos == cur.lastpos())
748                         --pos;
749                 else // potentional bug... BUG (Lgb)
750                         if (par.isSeparator(pos)) {
751                                 if (pos > cur.textRow().pos() &&
752                                     bidi.level(pos) % 2 ==
753                                     bidi.level(pos - 1) % 2)
754                                         --pos;
755                                 else if (pos + 1 < cur.lastpos())
756                                         ++pos;
757                         }
758         }
759
760         BufferParams const & bufparams = cur.buffer().params();
761         current_font = par.getFontSettings(bufparams, pos);
762         real_current_font = getFont(par, pos);
763
764         if (cur.pos() == cur.lastpos()
765             && bidi.isBoundary(cur.buffer(), par, cur.pos())
766             && !cur.boundary()) {
767                 Language const * lang = par.getParLanguage(bufparams);
768                 current_font.setLanguage(lang);
769                 current_font.setNumber(LyXFont::OFF);
770                 real_current_font.setLanguage(lang);
771                 real_current_font.setNumber(LyXFont::OFF);
772         }
773 }
774
775
776 // x is an absolute screen coord
777 // returns the column near the specified x-coordinate of the row
778 // x is set to the real beginning of this column
779 pos_type LyXText::getColumnNearX(pit_type const pit,
780                                  Row const & row, int & x, bool & boundary) const
781 {
782         int const xo = bv()->coordCache().get(this, pit).x_;
783         x -= xo;
784         RowMetrics const r = computeRowMetrics(pit, row);
785         Paragraph const & par = pars_[pit];
786
787         pos_type vc = row.pos();
788         pos_type end = row.endpos();
789         pos_type c = 0;
790         LyXLayout_ptr const & layout = par.layout();
791
792         bool left_side = false;
793
794         pos_type body_pos = par.beginOfBody();
795
796         double tmpx = r.x;
797         double last_tmpx = tmpx;
798
799         if (body_pos > 0 &&
800             (body_pos > end || !par.isLineSeparator(body_pos - 1)))
801                 body_pos = 0;
802
803         // check for empty row
804         if (vc == end) {
805                 x = int(tmpx) + xo;
806                 return 0;
807         }
808
809         lyx::frontend::FontMetrics const & fm 
810                 = theFontMetrics(getLabelFont(par));
811
812         while (vc < end && tmpx <= x) {
813                 c = bidi.vis2log(vc);
814                 last_tmpx = tmpx;
815                 if (body_pos > 0 && c == body_pos - 1) {
816                         // FIXME UNICODE
817                         docstring const lsep = lyx::from_utf8(layout->labelsep);
818                         tmpx += r.label_hfill + fm.width(lsep);
819                         if (par.isLineSeparator(body_pos - 1))
820                                 tmpx -= singleWidth(par, body_pos - 1);
821                 }
822
823                 if (hfillExpansion(par, row, c)) {
824                         tmpx += singleWidth(par, c);
825                         if (c >= body_pos)
826                                 tmpx += r.hfill;
827                         else
828                                 tmpx += r.label_hfill;
829                 } else if (par.isSeparator(c)) {
830                         tmpx += singleWidth(par, c);
831                         if (c >= body_pos)
832                                 tmpx += r.separator;
833                 } else {
834                         tmpx += singleWidth(par, c);
835                 }
836                 ++vc;
837         }
838
839         if ((tmpx + last_tmpx) / 2 > x) {
840                 tmpx = last_tmpx;
841                 left_side = true;
842         }
843
844         BOOST_ASSERT(vc <= end);  // This shouldn't happen.
845
846         boundary = false;
847         // This (rtl_support test) is not needed, but gives
848         // some speedup if rtl_support == false
849         bool const lastrow = lyxrc.rtl_support && row.endpos() == par.size();
850
851         // If lastrow is false, we don't need to compute
852         // the value of rtl.
853         bool const rtl = lastrow ? isRTL(par) : false;
854         if (lastrow &&
855             ((rtl  &&  left_side && vc == row.pos() && x < tmpx - 5) ||
856              (!rtl && !left_side && vc == end  && x > tmpx + 5)))
857                 c = end;
858         else if (vc == row.pos()) {
859                 c = bidi.vis2log(vc);
860                 if (bidi.level(c) % 2 == 1)
861                         ++c;
862         } else {
863                 c = bidi.vis2log(vc - 1);
864                 bool const rtl = (bidi.level(c) % 2 == 1);
865                 if (left_side == rtl) {
866                         ++c;
867                         boundary = bidi.isBoundary(*bv()->buffer(), par, c);
868                 }
869         }
870
871 // I believe this code is not needed anymore (Jug 20050717)
872 #if 0
873         // The following code is necessary because the cursor position past
874         // the last char in a row is logically equivalent to that before
875         // the first char in the next row. That's why insets causing row
876         // divisions -- Newline and display-style insets -- must be treated
877         // specially, so cursor up/down doesn't get stuck in an air gap -- MV
878         // Newline inset, air gap below:
879         if (row.pos() < end && c >= end && par.isNewline(end - 1)) {
880                 if (bidi.level(end -1) % 2 == 0)
881                         tmpx -= singleWidth(par, end - 1);
882                 else
883                         tmpx += singleWidth(par, end - 1);
884                 c = end - 1;
885         }
886
887         // Air gap above display inset:
888         if (row.pos() < end && c >= end && end < par.size()
889             && par.isInset(end) && par.getInset(end)->display()) {
890                 c = end - 1;
891         }
892         // Air gap below display inset:
893         if (row.pos() < end && c >= end && par.isInset(end - 1)
894             && par.getInset(end - 1)->display()) {
895                 c = end - 1;
896         }
897 #endif
898
899         x = int(tmpx) + xo;
900         pos_type const col = c - row.pos();
901
902         if (!c || end == par.size())
903                 return col;
904
905         if (c==end && !par.isLineSeparator(c-1) && !par.isNewline(c-1)) {
906                 boundary = true;
907                 return col;
908         }
909
910         return min(col, end - 1 - row.pos());
911 }
912
913
914 // y is screen coordinate
915 pit_type LyXText::getPitNearY(int y) const
916 {
917         BOOST_ASSERT(!paragraphs().empty());
918         BOOST_ASSERT(bv()->coordCache().getParPos().find(this) != bv()->coordCache().getParPos().end());
919         CoordCache::InnerParPosCache const & cc = bv()->coordCache().getParPos().find(this)->second;
920         lyxerr[Debug::DEBUG]
921                 << BOOST_CURRENT_FUNCTION
922                 << ": y: " << y << " cache size: " << cc.size()
923                 << endl;
924
925         // look for highest numbered paragraph with y coordinate less than given y
926         pit_type pit = 0;
927         int yy = -1;
928         CoordCache::InnerParPosCache::const_iterator it = cc.begin();
929         CoordCache::InnerParPosCache::const_iterator et = cc.end();
930         for (; it != et; ++it) {
931                 lyxerr[Debug::DEBUG]
932                         << BOOST_CURRENT_FUNCTION
933                         << "  examining: pit: " << it->first
934                         << " y: " << it->second.y_
935                         << endl;
936
937                 if (it->first >= pit && int(it->second.y_) - int(pars_[it->first].ascent()) <= y) {
938                         pit = it->first;
939                         yy = it->second.y_;
940                 }
941         }
942
943         lyxerr[Debug::DEBUG]
944                 << BOOST_CURRENT_FUNCTION
945                 << ": found best y: " << yy << " for pit: " << pit
946                 << endl;
947
948         return pit;
949 }
950
951
952 Row const & LyXText::getRowNearY(int y, pit_type pit) const
953 {
954         Paragraph const & par = pars_[pit];
955         int yy = bv()->coordCache().get(this, pit).y_ - par.ascent();
956         BOOST_ASSERT(!par.rows().empty());
957         RowList::const_iterator rit = par.rows().begin();
958         RowList::const_iterator const rlast = boost::prior(par.rows().end());
959         for (; rit != rlast; yy += rit->height(), ++rit)
960                 if (yy + rit->height() > y)
961                         break;
962         return *rit;
963 }
964
965
966 // x,y are absolute screen coordinates
967 // sets cursor recursively descending into nested editable insets
968 InsetBase * LyXText::editXY(LCursor & cur, int x, int y)
969 {
970         pit_type pit = getPitNearY(y);
971         BOOST_ASSERT(pit != -1);
972         Row const & row = getRowNearY(y, pit);
973         bool bound = false;
974
975         int xx = x; // is modified by getColumnNearX
976         pos_type const pos = row.pos() + getColumnNearX(pit, row, xx, bound);
977         cur.pit() = pit;
978         cur.pos() = pos;
979         cur.boundary(bound);
980         cur.x_target() = x;
981
982         // try to descend into nested insets
983         InsetBase * inset = checkInsetHit(x, y);
984         //lyxerr << "inset " << inset << " hit at x: " << x << " y: " << y << endl;
985         if (!inset) {
986                 // Either we deconst editXY or better we move current_font
987                 // and real_current_font to LCursor
988                 setCurrentFont(cur);
989                 return 0;
990         }
991
992         // This should be just before or just behind the
993         // cursor position set above.
994         BOOST_ASSERT((pos != 0 && inset == pars_[pit].getInset(pos - 1))
995                      || inset == pars_[pit].getInset(pos));
996         // Make sure the cursor points to the position before
997         // this inset.
998         if (inset == pars_[pit].getInset(pos - 1))
999                 --cur.pos();
1000         inset = inset->editXY(cur, x, y);
1001         if (cur.top().text() == this)
1002                 setCurrentFont(cur);
1003         return inset;
1004 }
1005
1006
1007 bool LyXText::checkAndActivateInset(LCursor & cur, bool front)
1008 {
1009         if (cur.selection())
1010                 return false;
1011         if (cur.pos() == cur.lastpos())
1012                 return false;
1013         InsetBase * inset = cur.nextInset();
1014         if (!isHighlyEditableInset(inset))
1015                 return false;
1016         inset->edit(cur, front);
1017         return true;
1018 }
1019
1020
1021 bool LyXText::cursorLeft(LCursor & cur)
1022 {
1023         if (!cur.boundary() && cur.pos() > 0 &&
1024             cur.textRow().pos() == cur.pos() &&
1025             !cur.paragraph().isLineSeparator(cur.pos()-1) &&
1026             !cur.paragraph().isNewline(cur.pos()-1)) {
1027                 return setCursor(cur, cur.pit(), cur.pos(), true, true);
1028         }
1029         if (cur.pos() != 0) {
1030                 bool boundary = cur.boundary();
1031                 bool updateNeeded = setCursor(cur, cur.pit(), cur.pos() - 1, true, false);
1032                 if (!checkAndActivateInset(cur, false)) {
1033                         if (false && !boundary &&
1034                             bidi.isBoundary(cur.buffer(), cur.paragraph(), cur.pos() + 1))
1035                                 updateNeeded |=
1036                                         setCursor(cur, cur.pit(), cur.pos() + 1, true, true);
1037                 }
1038                 return updateNeeded;
1039         }
1040
1041         if (cur.pit() != 0) {
1042                 // Steps into the paragraph above
1043                 return setCursor(cur, cur.pit() - 1, getPar(cur.pit() - 1).size());
1044         }
1045         return false;
1046 }
1047
1048
1049 bool LyXText::cursorRight(LCursor & cur)
1050 {
1051         if (cur.pos() != cur.lastpos()) {
1052                 if (cur.boundary())
1053                         return setCursor(cur, cur.pit(), cur.pos(),
1054                                          true, false);
1055
1056                 bool updateNeeded = false;
1057                 if (!checkAndActivateInset(cur, true)) {
1058                         if (cur.textRow().endpos() == cur.pos() + 1 &&
1059                             cur.textRow().endpos() != cur.lastpos() &&
1060                             !cur.paragraph().isLineSeparator(cur.pos()) &&
1061                             !cur.paragraph().isNewline(cur.pos())) {
1062                                 cur.boundary(true);
1063                         }
1064                         updateNeeded |= setCursor(cur, cur.pit(), cur.pos() + 1, true, cur.boundary());
1065                         if (false && bidi.isBoundary(cur.buffer(), cur.paragraph(),
1066                                                      cur.pos()))
1067                                 updateNeeded |= setCursor(cur, cur.pit(), cur.pos(), true, true);
1068                 }
1069                 return updateNeeded;
1070         }
1071
1072         if (cur.pit() != cur.lastpit())
1073                 return setCursor(cur, cur.pit() + 1, 0);
1074         return false;
1075 }
1076
1077
1078 bool LyXText::cursorUp(LCursor & cur)
1079 {
1080         Paragraph const & par = cur.paragraph();
1081         int row;
1082         int const x = cur.targetX();
1083
1084         if (cur.pos() && cur.boundary())
1085                 row = par.pos2row(cur.pos()-1);
1086         else
1087                 row = par.pos2row(cur.pos());
1088
1089         if (!cur.selection()) {
1090                 int const y = bv_funcs::getPos(cur.bv(), cur, cur.boundary()).y_;
1091                 LCursor old = cur;
1092                 // Go to middle of previous row. 16 found to work OK;
1093                 // 12 = top/bottom margin of display math
1094                 int const margin = 3 * InsetMathHull::displayMargin() / 2;
1095                 editXY(cur, x, y - par.rows()[row].ascent() - margin);
1096                 cur.clearSelection();
1097
1098                 // This happens when you move out of an inset.
1099                 // And to give the DEPM the possibility of doing
1100                 // something we must provide it with two different
1101                 // cursors. (Lgb)
1102                 LCursor dummy = cur;
1103                 if (dummy == old)
1104                         ++dummy.pos();
1105
1106                 return deleteEmptyParagraphMechanism(dummy, old);
1107         }
1108
1109         bool updateNeeded = false;
1110
1111         if (row > 0) {
1112                 updateNeeded |= setCursor(cur, cur.pit(),
1113                                           x2pos(cur.pit(), row - 1, x));
1114         } else if (cur.pit() > 0) {
1115                 --cur.pit();
1116                 //cannot use 'par' now
1117                 updateNeeded |= setCursor(cur, cur.pit(),
1118                                           x2pos(cur.pit(), cur.paragraph().rows().size() - 1, x));
1119         }
1120
1121         cur.x_target() = x;
1122
1123         return updateNeeded;
1124 }
1125
1126
1127 bool LyXText::cursorDown(LCursor & cur)
1128 {
1129         Paragraph const & par = cur.paragraph();
1130         int row;
1131         int const x = cur.targetX();
1132
1133         if (cur.pos() && cur.boundary())
1134                 row = par.pos2row(cur.pos()-1);
1135         else
1136                 row = par.pos2row(cur.pos());
1137
1138         if (!cur.selection()) {
1139                 int const y = bv_funcs::getPos(cur.bv(), cur, cur.boundary()).y_;
1140                 LCursor old = cur;
1141                 // To middle of next row
1142                 int const margin = 3 * InsetMathHull::displayMargin() / 2;
1143                 editXY(cur, x, y + par.rows()[row].descent() + margin);
1144                 cur.clearSelection();
1145
1146                 // This happens when you move out of an inset.
1147                 // And to give the DEPM the possibility of doing
1148                 // something we must provide it with two different
1149                 // cursors. (Lgb)
1150                 LCursor dummy = cur;
1151                 if (dummy == old)
1152                         ++dummy.pos();
1153
1154                 bool const changed = deleteEmptyParagraphMechanism(dummy, old);
1155
1156                 // Make sure that cur gets back whatever happened to dummy(Lgb)
1157                 if (changed)
1158                         cur = dummy;
1159
1160                 return changed;
1161         }
1162
1163         bool updateNeeded = false;
1164
1165         if (row + 1 < int(par.rows().size())) {
1166                 updateNeeded |= setCursor(cur, cur.pit(),
1167                                           x2pos(cur.pit(), row + 1, x));
1168         } else if (cur.pit() + 1 < int(paragraphs().size())) {
1169                 ++cur.pit();
1170                 updateNeeded |= setCursor(cur, cur.pit(),
1171                                           x2pos(cur.pit(), 0, x));
1172         }
1173
1174         cur.x_target() = x;
1175
1176         return updateNeeded;
1177 }
1178
1179
1180 bool LyXText::cursorUpParagraph(LCursor & cur)
1181 {
1182         bool updated = false;
1183         if (cur.pos() > 0)
1184                 updated = setCursor(cur, cur.pit(), 0);
1185         else if (cur.pit() != 0)
1186                 updated = setCursor(cur, cur.pit() - 1, 0);
1187         return updated;
1188 }
1189
1190
1191 bool LyXText::cursorDownParagraph(LCursor & cur)
1192 {
1193         bool updated = false;
1194         if (cur.pit() != cur.lastpit())
1195                 updated = setCursor(cur, cur.pit() + 1, 0);
1196         else
1197                 updated = setCursor(cur, cur.pit(), cur.lastpos());
1198         return updated;
1199 }
1200
1201
1202 // fix the cursor `cur' after a characters has been deleted at `where'
1203 // position. Called by deleteEmptyParagraphMechanism
1204 void LyXText::fixCursorAfterDelete(CursorSlice & cur, CursorSlice const & where)
1205 {
1206         // Do nothing if cursor is not in the paragraph where the
1207         // deletion occured,
1208         if (cur.pit() != where.pit())
1209                 return;
1210
1211         // If cursor position is after the deletion place update it
1212         if (cur.pos() > where.pos())
1213                 --cur.pos();
1214
1215         // Check also if we don't want to set the cursor on a spot behind the
1216         // pagragraph because we erased the last character.
1217         if (cur.pos() > cur.lastpos())
1218                 cur.pos() = cur.lastpos();
1219 }
1220
1221
1222 bool LyXText::deleteEmptyParagraphMechanism(LCursor & cur, LCursor & old)
1223 {
1224         // Would be wrong to delete anything if we have a selection.
1225         if (cur.selection())
1226                 return false;
1227
1228         //lyxerr[Debug::DEBUG] << "DEPM: cur:\n" << cur << "old:\n" << old << endl;
1229         // old should point to us
1230         BOOST_ASSERT(old.text() == this);
1231
1232         Paragraph & oldpar = old.paragraph();
1233
1234         // We allow all kinds of "mumbo-jumbo" when freespacing.
1235         if (oldpar.isFreeSpacing())
1236                 return false;
1237
1238         /* Ok I'll put some comments here about what is missing.
1239            There are still some small problems that can lead to
1240            double spaces stored in the document file or space at
1241            the beginning of paragraphs(). This happens if you have
1242            the cursor between to spaces and then save. Or if you
1243            cut and paste and the selection have a space at the
1244            beginning and then save right after the paste. (Lgb)
1245         */
1246
1247         // If old.pos() == 0 and old.pos()(1) == LineSeparator
1248         // delete the LineSeparator.
1249         // MISSING
1250
1251         // If old.pos() == 1 and old.pos()(0) == LineSeparator
1252         // delete the LineSeparator.
1253         // MISSING
1254
1255         bool const same_inset = &old.inset() == &cur.inset();
1256         bool const same_par = same_inset && old.pit() == cur.pit();
1257         bool const same_par_pos = same_par && old.pos() == cur.pos();
1258
1259         // If the chars around the old cursor were spaces, delete one of them.
1260         if (!same_par_pos) {
1261                 // Only if the cursor has really moved.
1262                 if (old.pos() > 0
1263                     && old.pos() < oldpar.size()
1264                     && oldpar.isLineSeparator(old.pos())
1265                     && oldpar.isLineSeparator(old.pos() - 1)
1266                     && oldpar.lookupChange(old.pos() - 1).type != Change::DELETED) {
1267                         oldpar.erase(old.pos() - 1, false); // do not track changes in DEPM
1268 #ifdef WITH_WARNINGS
1269 #warning This will not work anymore when we have multiple views of the same buffer
1270 // In this case, we will have to correct also the cursors held by
1271 // other bufferviews. It will probably be easier to do that in a more
1272 // automated way in CursorSlice code. (JMarc 26/09/2001)
1273 #endif
1274                         // correct all cursor parts
1275                         if (same_par) {
1276                                 fixCursorAfterDelete(cur.top(), old.top());
1277                                 cur.resetAnchor();
1278                         }
1279                         return true;
1280                 }
1281         }
1282
1283         // only do our magic if we changed paragraph
1284         if (same_par)
1285                 return false;
1286
1287         // don't delete anything if this is the ONLY paragraph!
1288         if (old.lastpit() == 0)
1289                 return false;
1290
1291         // Do not delete empty paragraphs with keepempty set.
1292         if (oldpar.allowEmpty())
1293                 return false;
1294
1295         if (oldpar.empty() || (oldpar.size() == 1 && oldpar.isLineSeparator(0))) {
1296                 // Delete old par.
1297                 recordUndo(old, Undo::ATOMIC,
1298                            max(old.pit() - 1, pit_type(0)),
1299                            min(old.pit() + 1, old.lastpit()));
1300                 ParagraphList & plist = old.text()->paragraphs();
1301                 plist.erase(boost::next(plist.begin(), old.pit()));
1302
1303                 // see #warning above
1304                 if (cur.depth() >= old.depth()) {
1305                         CursorSlice & curslice = cur[old.depth() - 1];
1306                         if (&curslice.inset() == &old.inset()
1307                             && curslice.pit() > old.pit()) {
1308                                 --curslice.pit();
1309                                 // since a paragraph has been deleted, all the
1310                                 // insets after `old' have been copied and
1311                                 // their address has changed. Therefore we
1312                                 // need to `regenerate' cur. (JMarc)
1313                                 cur.updateInsets(&(cur.bottom().inset()));
1314                                 cur.resetAnchor();
1315                         }
1316                 }
1317                 // There is a crash reported by Edwin Leuven (16/04/2006) because of:
1318                 //ParIterator par_it(old);
1319                 //updateLabels(old.buffer(), par_it);
1320                 // So for now we do the full update:
1321                 updateLabels(old.buffer());
1322                 return true;
1323         }
1324
1325         if (oldpar.stripLeadingSpaces())
1326                 cur.resetAnchor();
1327
1328         return false;
1329 }
1330
1331
1332 void LyXText::recUndo(pit_type first, pit_type last) const
1333 {
1334         recordUndo(bv()->cursor(), Undo::ATOMIC, first, last);
1335 }
1336
1337
1338 void LyXText::recUndo(pit_type par) const
1339 {
1340         recordUndo(bv()->cursor(), Undo::ATOMIC, par, par);
1341 }
1342
1343
1344 int defaultRowHeight()
1345 {
1346         return int(theFontMetrics(LyXFont(LyXFont::ALL_SANE)).maxHeight() *  1.2);
1347 }