]> git.lyx.org Git - lyx.git/blob - src/insets/insettext.C
parlist-2-a.diff
[lyx.git] / src / insets / insettext.C
1 /**
2  * \file insettext.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Jürgen Vigna
7  *
8  * Full author contact details are available in file CREDITS
9  */
10
11 #include <config.h>
12
13
14 #include "insettext.h"
15
16 #include "buffer.h"
17 #include "BufferView.h"
18 #include "CutAndPaste.h"
19 #include "debug.h"
20 #include "funcrequest.h"
21 #include "gettext.h"
22 #include "intl.h"
23 #include "LaTeXFeatures.h"
24 #include "LColor.h"
25 #include "lyxfont.h"
26 #include "lyxcursor.h"
27 #include "lyxfind.h"
28 #include "lyxlex.h"
29 #include "lyxrow.h"
30 #include "lyxrc.h"
31 #include "lyxtext.h"
32 #include "paragraph.h"
33 #include "ParagraphParameters.h"
34 #include "trans_mgr.h"
35 #include "undo_funcs.h"
36 #include "WordLangTuple.h"
37 #include "paragraph_funcs.h"
38 #include "sgml.h"
39 #include "rowpainter.h"
40 #include "insetnewline.h"
41
42 #include "frontends/Alert.h"
43 #include "frontends/Dialogs.h"
44 #include "frontends/font_metrics.h"
45 #include "frontends/LyXView.h"
46 #include "frontends/Painter.h"
47 #include "frontends/screen.h"
48
49 #include "support/textutils.h"
50 #include "support/LAssert.h"
51 #include "support/lstrings.h"
52 #include "support/lyxalgo.h" // lyx::count
53
54 #include <boost/bind.hpp>
55
56 #include <fstream>
57 #include <algorithm>
58 #include <cstdlib>
59 //#include <csignal>
60
61 using std::ostream;
62 using std::ifstream;
63 using std::endl;
64 using std::min;
65 using std::max;
66 using std::make_pair;
67 using std::vector;
68 using std::pair;
69 using std::for_each;
70
71 using lyx::pos_type;
72 using lyx::textclass_type;
73
74 // These functions should probably go into bufferview_funcs somehow (Jug)
75
76 void InsetText::saveLyXTextState(LyXText * t) const
77 {
78         // check if my paragraphs are still valid
79         ParagraphList::iterator it = paragraphs.begin();
80         ParagraphList::iterator end = paragraphs.end();
81         for (; it != end; ++it) {
82                 if (&*it == t->cursor.par())
83                         break;
84         }
85
86         if (it != end && t->cursor.pos() <= it->size()) {
87                 sstate.lpar = t->cursor.par();
88                 sstate.pos = t->cursor.pos();
89                 sstate.boundary = t->cursor.boundary();
90                 sstate.selstartpar = t->selection.start.par();
91                 sstate.selstartpos = t->selection.start.pos();
92                 sstate.selstartboundary = t->selection.start.boundary();
93                 sstate.selendpar = t->selection.end.par();
94                 sstate.selendpos = t->selection.end.pos();
95                 sstate.selendboundary = t->selection.end.boundary();
96                 sstate.selection = t->selection.set();
97                 sstate.mark_set = t->selection.mark();
98         } else {
99                 sstate.lpar = 0;
100         }
101 }
102
103
104 void InsetText::restoreLyXTextState(LyXText * t) const
105 {
106         if (!sstate.lpar)
107                 return;
108
109         t->selection.set(true);
110         /* at this point just to avoid the DEPM when setting the cursor */
111         t->selection.mark(sstate.mark_set);
112         if (sstate.selection) {
113                 t->setCursor(sstate.selstartpar, sstate.selstartpos,
114                              true, sstate.selstartboundary);
115                 t->selection.cursor = t->cursor;
116                 t->setCursor(sstate.selendpar, sstate.selendpos,
117                              true, sstate.selendboundary);
118                 t->setSelection();
119                 t->setCursor(sstate.lpar, sstate.pos);
120         } else {
121                 t->setCursor(sstate.lpar, sstate.pos, true, sstate.boundary);
122                 t->selection.cursor = t->cursor;
123                 t->selection.set(false);
124         }
125 }
126
127
128 InsetText::InnerCache::InnerCache(boost::shared_ptr<LyXText> t)
129 {
130         text = t;
131         remove = false;
132 }
133
134
135 InsetText::InsetText(BufferParams const & bp)
136         : UpdatableInset(), lt(0), in_update(false), do_resize(0),
137           do_reinit(false)
138 {
139         paragraphs.set(new Paragraph);
140         paragraphs.begin()->layout(bp.getLyXTextClass().defaultLayout());
141         if (bp.tracking_changes)
142                 paragraphs.begin()->trackChanges();
143         init();
144 }
145
146
147 InsetText::InsetText(InsetText const & in, bool same_id)
148         : UpdatableInset(in, same_id), lt(0), in_update(false), do_resize(0),
149           do_reinit(false)
150 {
151         init(&in, same_id);
152 }
153
154
155 InsetText & InsetText::operator=(InsetText const & it)
156 {
157         init(&it);
158         return * this;
159 }
160
161
162 void InsetText::init(InsetText const * ins, bool same_id)
163 {
164         if (ins) {
165                 setParagraphData(&*(ins->paragraphs.begin()), same_id);
166                 autoBreakRows = ins->autoBreakRows;
167                 drawFrame_ = ins->drawFrame_;
168                 frame_color = ins->frame_color;
169                 if (same_id)
170                         id_ = ins->id_;
171         } else {
172                 for_each(paragraphs.begin(), paragraphs.end(),
173                          boost::bind(&Paragraph::setInsetOwner, _1, this));
174
175                 the_locking_inset = 0;
176                 drawFrame_ = NEVER;
177                 frame_color = LColor::insetframe;
178                 autoBreakRows = false;
179         }
180         top_y = 0;
181         insetAscent = 0;
182         insetDescent = 0;
183         insetWidth = 0;
184         old_max_width = 0;
185         no_selection = true;
186         need_update = FULL;
187         drawTextXOffset = 0;
188         drawTextYOffset = 0;
189         locked = false;
190         old_par = 0;
191         last_drawn_width = -1;
192         cached_bview = 0;
193         sstate.lpar = 0;
194         in_insetAllowed = false;
195 }
196
197
198 InsetText::~InsetText()
199 {
200         paragraphs.clear();
201 }
202
203
204 void InsetText::clear(bool just_mark_erased)
205 {
206         if (just_mark_erased) {
207                 ParagraphList::iterator it = paragraphs.begin();
208                 ParagraphList::iterator end = paragraphs.end();
209                 for (; it != end; ++it) {
210                         it->markErased();
211                 }
212                 need_update = FULL;
213                 return;
214         }
215
216         // This is a gross hack...
217         LyXLayout_ptr old_layout = paragraphs.begin()->layout();
218
219         paragraphs.clear();
220         paragraphs.set(new Paragraph);
221         paragraphs.begin()->setInsetOwner(this);
222         paragraphs.begin()->layout(old_layout);
223
224         reinitLyXText();
225         need_update = INIT;
226 }
227
228
229 Inset * InsetText::clone(Buffer const &, bool same_id) const
230 {
231         return new InsetText(*this, same_id);
232 }
233
234
235 void InsetText::write(Buffer const * buf, ostream & os) const
236 {
237         os << "Text\n";
238         writeParagraphData(buf, os);
239 }
240
241
242 void InsetText::writeParagraphData(Buffer const * buf, ostream & os) const
243 {
244         ParagraphList::iterator it = paragraphs.begin();
245         ParagraphList::iterator end = paragraphs.end();
246         Paragraph::depth_type dth = 0;
247         for (; it != end; ++it) {
248                 it->write(buf, os, buf->params, dth);
249         }
250 }
251
252
253 void InsetText::read(Buffer const * buf, LyXLex & lex)
254 {
255         string token;
256         Paragraph::depth_type depth = 0;
257
258         clear(false);
259
260         if (buf->params.tracking_changes)
261                 paragraphs.begin()->trackChanges();
262
263         // delete the initial paragraph
264         paragraphs.clear();
265         ParagraphList::iterator pit = paragraphs.begin();
266
267         while (lex.isOK()) {
268                 lex.nextToken();
269                 token = lex.getString();
270                 if (token.empty())
271                         continue;
272                 if (token == "\\end_inset") {
273                         break;
274                 }
275
276                 if (token == "\\the_end") {
277                         lex.printError("\\the_end read in inset! Error in document!");
278                         return;
279                 }
280
281                 // FIXME: ugly.
282                 const_cast<Buffer*>(buf)->readParagraph(lex, token, paragraphs, pit, depth);
283         }
284
285         pit = paragraphs.begin();
286         ParagraphList::iterator const end = paragraphs.end();
287         for (; pit != end; ++pit)
288                 pit->setInsetOwner(this);
289
290         if (token != "\\end_inset") {
291                 lex.printError("Missing \\end_inset at this point. "
292                                            "Read: `$$Token'");
293         }
294         need_update = FULL;
295 }
296
297
298 int InsetText::ascent(BufferView * bv, LyXFont const &) const
299 {
300         insetAscent = getLyXText(bv)->rows().begin()->ascent_of_text() +
301                 TEXT_TO_INSET_OFFSET;
302         return insetAscent;
303 }
304
305
306 int InsetText::descent(BufferView * bv, LyXFont const &) const
307 {
308         LyXText * llt = getLyXText(bv);
309         insetDescent = llt->height - llt->rows().begin()->ascent_of_text() +
310                 TEXT_TO_INSET_OFFSET;
311         return insetDescent;
312 }
313
314
315 int InsetText::width(BufferView * bv, LyXFont const &) const
316 {
317         insetWidth = max(textWidth(bv), (int)getLyXText(bv)->width) +
318                 (2 * TEXT_TO_INSET_OFFSET);
319         insetWidth = max(insetWidth, 10);
320         return insetWidth;
321 }
322
323
324 int InsetText::textWidth(BufferView * bv, bool fordraw) const
325 {
326         int w;
327         if (!autoBreakRows) {
328                 w = -1;
329         } else {
330                 w = getMaxWidth(bv, this);
331         }
332         if (fordraw) {
333                 return max(w - (2 * TEXT_TO_INSET_OFFSET),
334                            (int)getLyXText(bv)->width);
335         } else if (w < 0) {
336             return -1;
337         }
338         return w - (2 * TEXT_TO_INSET_OFFSET);
339 }
340
341
342 void InsetText::draw(BufferView * bv, LyXFont const & f,
343                      int baseline, float & x) const
344 {
345         if (nodraw())
346                 return;
347
348         // update our idea of where we are. Clearly, we should
349         // not have to know this information.
350         if (top_x != int(x))
351                 top_x = int(x);
352
353         int const start_x = int(x);
354
355         Painter & pain = bv->painter();
356
357         // call these methods so that insetWidth, insetAscent and
358         // insetDescent have the right values.
359         width(bv, f);
360         ascent(bv, f);
361         descent(bv, f);
362
363         // repaint the background if needed
364         if (backgroundColor() != LColor::background)
365                 clearInset(bv, start_x + TEXT_TO_INSET_OFFSET, baseline);
366
367         // no draw is necessary !!!
368         if ((drawFrame_ == LOCKED) && !locked && paragraphs.begin()->empty()) {
369                 top_baseline = baseline;
370                 x += width(bv, f);
371                 need_update = NONE;
372                 return;
373         }
374
375         if (!owner())
376                 x += static_cast<float>(scroll());
377
378         top_baseline = baseline;
379         top_y = baseline - insetAscent;
380
381         if (last_drawn_width != insetWidth) {
382                 need_update |= FULL;
383                 last_drawn_width = insetWidth;
384         }
385
386         if (the_locking_inset && (cpar(bv) == inset_par)
387                 && (cpos(bv) == inset_pos)) {
388                 inset_x = cix(bv) - int(x) + drawTextXOffset;
389                 inset_y = ciy(bv) + drawTextYOffset;
390         }
391
392         bool clear = false;
393         if (!lt) {
394                 lt = getLyXText(bv);
395                 clear = true;
396         }
397         x += TEXT_TO_INSET_OFFSET;
398
399         RowList::iterator rowit = lt->rows().begin();
400         RowList::iterator end = lt->rows().end();
401
402         int y_offset = baseline - rowit->ascent_of_text();
403         int ph = pain.paperHeight();
404         int first = 0;
405         int y = y_offset;
406         while ((rowit != end) && ((y + rowit->height()) <= 0)) {
407                 y += rowit->height();
408                 first += rowit->height();
409                 ++rowit;
410         }
411         if (y_offset < 0) {
412                 lt->top_y(-y_offset);
413                 first = y;
414                 y_offset = 0;
415         } else {
416                 lt->top_y(first);
417                 first = 0;
418         }
419
420         int yf = y_offset + first;
421         y = 0;
422         while ((rowit != end) && (yf < ph)) {
423                 RowPainter rp(*bv, *lt, rowit);
424                 rp.paint(y + y_offset + first, int(x), y + lt->top_y());
425                 y += rowit->height();
426                 yf += rowit->height();
427                 ++rowit;
428         }
429
430         lt->clearPaint();
431
432         if ((drawFrame_ == ALWAYS) || (drawFrame_ == LOCKED && locked)) {
433                 drawFrame(pain, int(start_x));
434         }
435
436         x += insetWidth - TEXT_TO_INSET_OFFSET;
437
438         if (need_update != INIT) {
439                 need_update = NONE;
440         }
441         if (clear)
442                 lt = 0;
443 }
444
445
446 void InsetText::drawFrame(Painter & pain, int x) const
447 {
448         static int const ttoD2 = TEXT_TO_INSET_OFFSET / 2;
449         frame_x = x + ttoD2;
450         frame_y = top_baseline - insetAscent + ttoD2;
451         frame_w = insetWidth - TEXT_TO_INSET_OFFSET;
452         frame_h = insetAscent + insetDescent - TEXT_TO_INSET_OFFSET;
453         pain.rectangle(frame_x, frame_y, frame_w, frame_h,
454                        frame_color);
455 }
456
457
458 void InsetText::update(BufferView * bv, bool reinit)
459 {
460         if (in_update) {
461                 if (reinit && owner()) {
462                         reinitLyXText();
463                         owner()->update(bv, true);
464                 }
465                 return;
466         }
467         in_update = true;
468
469         if (reinit || need_update == INIT) {
470                 need_update = FULL;
471                 // we should put this call where we set need_update to INIT!
472                 reinitLyXText();
473                 if (owner())
474                         owner()->update(bv, true);
475                 in_update = false;
476
477                 int nw = getMaxWidth(bv, this);
478                 if (nw > 0 && old_max_width != nw) {
479                         need_update |= INIT;
480                         old_max_width = nw;
481                 }
482                 return;
483         }
484
485         if (!autoBreakRows &&
486             boost::next(paragraphs.begin()) != paragraphs.end())
487                 collapseParagraphs(bv);
488
489         if (the_locking_inset) {
490                 inset_x = cix(bv) - top_x + drawTextXOffset;
491                 inset_y = ciy(bv) + drawTextYOffset;
492                 the_locking_inset->update(bv, reinit);
493         }
494
495         bool clear = false;
496         if (!lt) {
497                 lt = getLyXText(bv);
498                 clear = true;
499         }
500         if ((need_update & CURSOR_PAR) && (lt->refreshStatus() == LyXText::REFRESH_NONE) &&
501                 the_locking_inset) {
502                 lt->updateInset(the_locking_inset);
503         }
504
505         if (lt->refreshStatus() == LyXText::REFRESH_AREA)
506                 need_update |= FULL;
507         if (clear)
508                 lt = 0;
509
510         in_update = false;
511
512         int nw = getMaxWidth(bv, this);
513         if (nw > 0 && old_max_width != nw) {
514                 need_update |= INIT;
515                 old_max_width = nw;
516         }
517 }
518
519
520 void InsetText::setUpdateStatus(BufferView * bv, int what) const
521 {
522         // this does nothing dangerous so use only a localized buffer
523         LyXText * llt = getLyXText(bv);
524
525         need_update |= what;
526         // we have to redraw us full if our LyXText REFRESH_AREA or
527         // if we don't break row so that we only have one row to update!
528         if ((llt->refreshStatus() == LyXText::REFRESH_AREA) ||
529             (!autoBreakRows &&
530              (llt->refreshStatus() == LyXText::REFRESH_ROW)))
531         {
532                 need_update |= FULL;
533         } else if (llt->refreshStatus() == LyXText::REFRESH_ROW) {
534                 need_update |= CURSOR_PAR;
535         }
536
537         // this to not draw a selection when we redraw all of it!
538         if (need_update & CURSOR && !(need_update & SELECTION)) {
539                 if (llt->selection.set())
540                         need_update = FULL;
541                 llt->clearSelection();
542         }
543 }
544
545
546 void InsetText::updateLocal(BufferView * bv, int what, bool mark_dirty)
547 {
548         if (!autoBreakRows &&
549             boost::next(paragraphs.begin()) != paragraphs.end())
550                 collapseParagraphs(bv);
551         bool clear = false;
552         if (!lt) {
553                 lt = getLyXText(bv);
554                 clear = true;
555         }
556         lt->fullRebreak();
557         setUpdateStatus(bv, what);
558         bool flag = mark_dirty ||
559                 (((need_update != CURSOR) && (need_update != NONE)) ||
560                  (lt->refreshStatus() != LyXText::REFRESH_NONE) || lt->selection.set());
561         if (!lt->selection.set())
562                 lt->selection.cursor = lt->cursor;
563
564         bv->fitCursor();
565
566         if (flag) {
567                 lt->postPaint(0);
568                 bv->updateInset(const_cast<InsetText *>(this));
569         }
570
571         if (clear)
572                 lt = 0;
573
574         if (need_update == CURSOR)
575                 need_update = NONE;
576         bv->owner()->view_state_changed();
577         bv->owner()->updateMenubar();
578         bv->owner()->updateToolbar();
579         if (old_par != cpar(bv)) {
580                 bv->owner()->setLayout(cpar(bv)->layout()->name());
581                 old_par = cpar(bv);
582         }
583 }
584
585
586 string const InsetText::editMessage() const
587 {
588         return _("Opened Text Inset");
589 }
590
591
592 void InsetText::edit(BufferView * bv, int x, int y, mouse_button::state button)
593 {
594         UpdatableInset::edit(bv, x, y, button);
595
596         if (!bv->lockInset(this)) {
597                 lyxerr[Debug::INSETS] << "Cannot lock inset" << endl;
598                 return;
599         }
600         locked = true;
601         the_locking_inset = 0;
602         inset_pos = inset_x = inset_y = 0;
603         inset_boundary = false;
604         inset_par = 0;
605         old_par = 0;
606         int tmp_y = (y < 0) ? 0 : y;
607         bool clear = false;
608         if (!lt) {
609                 lt = getLyXText(bv);
610                 clear = true;
611         }
612         // we put here -1 and not button as now the button in the
613         // edit call should not be needed we will fix this in 1.3.x
614         // cycle hopefully (Jug 20020509)
615         // FIXME: GUII I've changed this to none: probably WRONG
616         if (!checkAndActivateInset(bv, x, tmp_y, mouse_button::none)) {
617                 lt->setCursorFromCoordinates(x - drawTextXOffset,
618                                             y + insetAscent);
619                 lt->cursor.x_fix(lt->cursor.x());
620         }
621         lt->clearSelection();
622         finishUndo();
623         // If the inset is empty set the language of the current font to the
624         // language to the surronding text (if different).
625         if (paragraphs.begin()->empty() &&
626             boost::next(paragraphs.begin()) == paragraphs.end()&&
627                 bv->getParentLanguage(this) != lt->current_font.language())
628         {
629                 LyXFont font(LyXFont::ALL_IGNORE);
630                 font.setLanguage(bv->getParentLanguage(this));
631                 setFont(bv, font, false);
632         }
633         if (clear)
634                 lt = 0;
635
636         int code = CURSOR;
637         if (drawFrame_ == LOCKED)
638                 code = CURSOR|DRAW_FRAME;
639         updateLocal(bv, code, false);
640         showInsetCursor(bv);
641
642         // Tell the paragraph dialog that we've entered an insettext.
643         bv->dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
644 }
645
646
647 void InsetText::edit(BufferView * bv, bool front)
648 {
649         UpdatableInset::edit(bv, front);
650
651         if (!bv->lockInset(this)) {
652                 lyxerr[Debug::INSETS] << "Cannot lock inset" << endl;
653                 return;
654         }
655         locked = true;
656         the_locking_inset = 0;
657         inset_pos = inset_x = inset_y = 0;
658         inset_boundary = false;
659         inset_par = 0;
660         old_par = 0;
661         bool clear = false;
662         if (!lt) {
663                 lt = getLyXText(bv);
664                 clear = true;
665         }
666         if (front)
667                 lt->setCursor(&*(paragraphs.begin()), 0);
668         else {
669                 ParagraphList::iterator it = paragraphs.begin();
670                 ParagraphList::iterator end = paragraphs.end();
671                 while (boost::next(it) != end)
672                         ++it;
673 //              int const pos = (p->size() ? p->size()-1 : p->size());
674                 lt->setCursor(&*it, it->size());
675         }
676         lt->clearSelection();
677         finishUndo();
678         // If the inset is empty set the language of the current font to the
679         // language to the surronding text (if different).
680         if (paragraphs.begin()->empty() &&
681             boost::next(paragraphs.begin()) == paragraphs.end() &&
682                 bv->getParentLanguage(this) != lt->current_font.language()) {
683                 LyXFont font(LyXFont::ALL_IGNORE);
684                 font.setLanguage(bv->getParentLanguage(this));
685                 setFont(bv, font, false);
686         }
687         if (clear)
688                 lt = 0;
689         int code = CURSOR;
690         if (drawFrame_ == LOCKED)
691                 code = CURSOR|DRAW_FRAME;
692         updateLocal(bv, code, false);
693         showInsetCursor(bv);
694 }
695
696
697 void InsetText::insetUnlock(BufferView * bv)
698 {
699         if (the_locking_inset) {
700                 the_locking_inset->insetUnlock(bv);
701                 the_locking_inset = 0;
702                 updateLocal(bv, CURSOR_PAR, false);
703         }
704         hideInsetCursor(bv);
705         no_selection = true;
706         locked = false;
707         int code = NONE;
708         bool clear = false;
709
710         if (!lt) {
711                 lt = getLyXText(bv);
712                 clear = true;
713         }
714         if (lt->selection.set()) {
715                 lt->clearSelection();
716                 code = FULL;
717         } else if (owner()) {
718                 bv->owner()->setLayout(owner()->getLyXText(bv)
719                                        ->cursor.par()->layout()->name());
720         } else
721                 bv->owner()->setLayout(bv->text->cursor.par()->layout()->name());
722         // hack for deleteEmptyParMech
723         if (!paragraphs.begin()->empty()) {
724                 lt->setCursor(&*(paragraphs.begin()), 0);
725         } else if (boost::next(paragraphs.begin()) != paragraphs.end()) {
726                 lt->setCursor(&*boost::next(paragraphs.begin()), 0);
727         }
728         if (clear)
729                 lt = 0;
730 #if 0
731         updateLocal(bv, code, false);
732 #else
733         if (code != NONE)
734                 setUpdateStatus(bv, code);
735 #endif
736 }
737
738
739 void InsetText::lockInset(BufferView * bv)
740 {
741         locked = true;
742         the_locking_inset = 0;
743         inset_pos = inset_x = inset_y = 0;
744         inset_boundary = false;
745         inset_par = 0;
746         old_par = 0;
747         bool clear = false;
748         if (!lt) {
749                 lt = getLyXText(bv);
750                 clear = true;
751         }
752         lt->setCursor(&*(paragraphs.begin()), 0);
753         lt->clearSelection();
754         finishUndo();
755         // If the inset is empty set the language of the current font to the
756         // language to the surronding text (if different).
757         if (paragraphs.begin()->empty() &&
758             boost::next(paragraphs.begin()) == paragraphs.end() &&
759                 bv->getParentLanguage(this) != lt->current_font.language()) {
760                 LyXFont font(LyXFont::ALL_IGNORE);
761                 font.setLanguage(bv->getParentLanguage(this));
762                 setFont(bv, font, false);
763         }
764         if (clear)
765                 lt = 0;
766         int code = CURSOR;
767         if (drawFrame_ == LOCKED)
768                 code = CURSOR|DRAW_FRAME;
769         setUpdateStatus(bv, code);
770 }
771
772
773 void InsetText::lockInset(BufferView * bv, UpdatableInset * inset)
774 {
775         the_locking_inset = inset;
776         inset_x = cix(bv) - top_x + drawTextXOffset;
777         inset_y = ciy(bv) + drawTextYOffset;
778         inset_pos = cpos(bv);
779         inset_par = cpar(bv);
780         inset_boundary = cboundary(bv);
781         updateLocal(bv, CURSOR, false);
782 }
783
784
785 bool InsetText::lockInsetInInset(BufferView * bv, UpdatableInset * inset)
786 {
787         lyxerr[Debug::INSETS] << "InsetText::LockInsetInInset("
788                               << inset << "): ";
789         if (!inset)
790                 return false;
791         if (!the_locking_inset) {
792                 ParagraphList::iterator pit = paragraphs.begin();
793                 ParagraphList::iterator pend = paragraphs.end();
794
795                 int const id = inset->id();
796                 for (; pit != pend; ++pit) {
797                         InsetList::iterator it =
798                                 pit->insetlist.begin();
799                         InsetList::iterator const end =
800                                 pit->insetlist.end();
801                         for (; it != end; ++it) {
802                                 if (it.getInset() == inset) {
803                                         getLyXText(bv)->setCursorIntern(&*pit, it.getPos());
804                                         lockInset(bv, inset);
805                                         return true;
806                                 }
807                                 if (it.getInset()->getInsetFromID(id)) {
808                                         getLyXText(bv)->setCursorIntern(&*pit, it.getPos());
809                                         it.getInset()->edit(bv);
810                                         return the_locking_inset->lockInsetInInset(bv, inset);
811                                 }
812                         }
813                 }
814                 return false;
815         }
816         if (inset == cpar(bv)->getInset(cpos(bv))) {
817                 lyxerr[Debug::INSETS] << "OK" << endl;
818                 lockInset(bv, inset);
819                 return true;
820         } else if (the_locking_inset && (the_locking_inset == inset)) {
821                 if (cpar(bv) == inset_par && cpos(bv) == inset_pos) {
822                         lyxerr[Debug::INSETS] << "OK" << endl;
823                         inset_x = cix(bv) - top_x + drawTextXOffset;
824                         inset_y = ciy(bv) + drawTextYOffset;
825                 } else {
826                         lyxerr[Debug::INSETS] << "cursor.pos != inset_pos" << endl;
827                 }
828         } else if (the_locking_inset) {
829                 lyxerr[Debug::INSETS] << "MAYBE" << endl;
830                 return the_locking_inset->lockInsetInInset(bv, inset);
831         }
832         lyxerr[Debug::INSETS] << "NOT OK" << endl;
833         return false;
834 }
835
836
837 bool InsetText::unlockInsetInInset(BufferView * bv, UpdatableInset * inset,
838                                    bool lr)
839 {
840         if (!the_locking_inset)
841                 return false;
842         if (the_locking_inset == inset) {
843                 the_locking_inset->insetUnlock(bv);
844                 getLyXText(bv)->updateInset(inset);
845                 the_locking_inset = 0;
846                 if (lr)
847                         moveRightIntern(bv, true, false);
848                 old_par = 0; // force layout setting
849                 if (scroll())
850                         scroll(bv, 0.0F);
851                 else
852                         updateLocal(bv, CURSOR, false);
853                 return true;
854         }
855         return the_locking_inset->unlockInsetInInset(bv, inset, lr);
856 }
857
858
859 bool InsetText::updateInsetInInset(BufferView * bv, Inset * inset)
860 {
861         if (!autoBreakRows &&
862             boost::next(paragraphs.begin()) != paragraphs.end())
863                 collapseParagraphs(bv);
864         if (inset == this)
865                 return true;
866         bool clear = false;
867         if (!lt) {
868                 lt = getLyXText(bv);
869                 clear = true;
870         }
871         if (inset->owner() != this) {
872                 int ustat = CURSOR_PAR;
873                 bool found = false;
874                 UpdatableInset * tl_inset = the_locking_inset;
875                 if (tl_inset)
876                         found = tl_inset->updateInsetInInset(bv, inset);
877                 if (!found) {
878                         tl_inset = static_cast<UpdatableInset *>(inset);
879                         while(tl_inset->owner() && tl_inset->owner() != this)
880                                 tl_inset = static_cast<UpdatableInset *>(tl_inset->owner());
881                         if (!tl_inset->owner())
882                                 return false;
883                         found = tl_inset->updateInsetInInset(bv, inset);
884                         ustat = FULL;
885                 }
886                 if (found)
887                         lt->updateInset(tl_inset);
888                 if (clear)
889                         lt = 0;
890                 if (found)
891                         setUpdateStatus(bv, ustat);
892                 return found;
893         }
894         bool found = lt->updateInset(inset);
895         if (clear)
896                 lt = 0;
897         if (found) {
898                 setUpdateStatus(bv, CURSOR_PAR);
899                 if (the_locking_inset &&
900                     cpar(bv) == inset_par && cpos(bv) == inset_pos)
901                 {
902                         inset_x = cix(bv) - top_x + drawTextXOffset;
903                         inset_y = ciy(bv) + drawTextYOffset;
904                 }
905         }
906         return found;
907 }
908
909
910 void InsetText::lfunMousePress(FuncRequest const & cmd)
911 {
912         no_selection = true;
913
914         // use this to check mouse motion for selection!
915         mouse_x = cmd.x;
916         mouse_y = cmd.y;
917
918         BufferView * bv = cmd.view();
919         FuncRequest cmd1 = cmd;
920         cmd1.x -= inset_x;
921         cmd1.y -= inset_y;
922         if (!locked)
923                 lockInset(bv);
924
925         int tmp_x = cmd.x - drawTextXOffset;
926         int tmp_y = cmd.y + insetAscent - getLyXText(bv)->top_y();
927         Inset * inset = getLyXText(bv)->checkInsetHit(tmp_x, tmp_y);
928
929         hideInsetCursor(bv);
930         if (the_locking_inset) {
931                 if (the_locking_inset == inset) {
932                         the_locking_inset->localDispatch(cmd1);
933                         return;
934                 }
935                 // otherwise only unlock the_locking_inset
936                 the_locking_inset->insetUnlock(bv);
937                 the_locking_inset = 0;
938         }
939         if (!inset)
940                 no_selection = false;
941
942         if (bv->theLockingInset()) {
943                 if (isHighlyEditableInset(inset)) {
944                         // We just have to lock the inset before calling a
945                         // PressEvent on it!
946                         UpdatableInset * uinset = static_cast<UpdatableInset*>(inset);
947                         if (!bv->lockInset(uinset)) {
948                                 lyxerr[Debug::INSETS] << "Cannot lock inset" << endl;
949                         }
950                         inset->localDispatch(cmd1);
951                         if (the_locking_inset)
952                                 updateLocal(bv, CURSOR, false);
953                         return;
954                 }
955         }
956         if (!inset) {
957                 bool paste_internally = false;
958                 if (cmd.button() == mouse_button::button2 && getLyXText(bv)->selection.set()) {
959                         localDispatch(FuncRequest(bv, LFUN_COPY));
960                         paste_internally = true;
961                 }
962                 bool clear = false;
963                 if (!lt) {
964                         lt = getLyXText(bv);
965                         clear = true;
966                 }
967                 int old_top_y = lt->top_y();
968
969                 lt->setCursorFromCoordinates(cmd.x - drawTextXOffset,
970                                              cmd.y + insetAscent);
971                 // set the selection cursor!
972                 lt->selection.cursor = lt->cursor;
973                 lt->cursor.x_fix(lt->cursor.x());
974
975                 if (lt->selection.set()) {
976                         lt->clearSelection();
977                         updateLocal(bv, FULL, false);
978                 } else {
979                         lt->clearSelection();
980                         updateLocal(bv, CURSOR, false);
981                 }
982
983                 if (clear)
984                         lt = 0;
985
986                 bv->owner()->setLayout(cpar(bv)->layout()->name());
987
988                 // we moved the view we cannot do mouse selection in this case!
989                 if (getLyXText(bv)->top_y() != old_top_y)
990                         no_selection = true;
991                 old_par = cpar(bv);
992                 // Insert primary selection with middle mouse
993                 // if there is a local selection in the current buffer,
994                 // insert this
995                 if (cmd.button() == mouse_button::button2) {
996                         if (paste_internally)
997                                 localDispatch(FuncRequest(bv, LFUN_PASTE));
998                         else
999                                 localDispatch(FuncRequest(bv, LFUN_PASTESELECTION, "paragraph"));
1000                 }
1001         } else {
1002                 getLyXText(bv)->clearSelection();
1003         }
1004         showInsetCursor(bv);
1005 }
1006
1007
1008 bool InsetText::lfunMouseRelease(FuncRequest const & cmd)
1009 {
1010         BufferView * bv = cmd.view();
1011         FuncRequest cmd1 = cmd;
1012         cmd1.x -= inset_x;
1013         cmd1.y -= inset_y;
1014
1015         no_selection = true;
1016         if (the_locking_inset)
1017                 return the_locking_inset->localDispatch(cmd1);
1018
1019         int tmp_x = cmd.x - drawTextXOffset;
1020         int tmp_y = cmd.y + insetAscent - getLyXText(bv)->top_y();
1021         Inset * inset = getLyXText(bv)->checkInsetHit(tmp_x, tmp_y);
1022         bool ret = false;
1023         if (inset) {
1024 // This code should probably be removed now. Simple insets
1025 // (!highlyEditable) can actually take the localDispatch,
1026 // and turn it into edit() if necessary. But we still
1027 // need to deal properly with the whole relative vs.
1028 // absolute mouse co-ords thing in a realiable, sensible way
1029 #if 0
1030                 if (isHighlyEditableInset(inset))
1031                         ret = inset->localDispatch(cmd1);
1032                 else {
1033                         inset_x = cix(bv) - top_x + drawTextXOffset;
1034                         inset_y = ciy(bv) + drawTextYOffset;
1035                         cmd1.x = cmd.x - inset_x;
1036                         cmd1.y = cmd.x - inset_y;
1037                         inset->edit(bv, cmd1.x, cmd1.y, cmd.button());
1038                         ret = true;
1039                 }
1040 #endif
1041                 ret = inset->localDispatch(cmd1);
1042                 updateLocal(bv, CURSOR_PAR, false);
1043
1044         }
1045         return ret;
1046 }
1047
1048
1049 void InsetText::lfunMouseMotion(FuncRequest const & cmd)
1050 {
1051         FuncRequest cmd1 = cmd;
1052         cmd1.x -= inset_x;
1053         cmd1.y -= inset_y;
1054
1055         if (the_locking_inset) {
1056                 the_locking_inset->localDispatch(cmd1);
1057                 return;
1058         }
1059
1060         if (no_selection || (mouse_x == cmd.x && mouse_y == cmd.y))
1061                 return;
1062
1063         BufferView * bv = cmd.view();
1064         bool clear = false;
1065         if (!lt) {
1066                 lt = getLyXText(bv);
1067                 clear = true;
1068         }
1069         hideInsetCursor(bv);
1070         LyXCursor cur = lt->cursor;
1071         lt->setCursorFromCoordinates
1072                 (cmd.x - drawTextXOffset, cmd.y + insetAscent);
1073         lt->cursor.x_fix(lt->cursor.x());
1074         if (cur == lt->cursor) {
1075                 if (clear)
1076                         lt = 0;
1077                 return;
1078         }
1079         lt->setSelection();
1080         bool flag = (lt->toggle_cursor.par() != lt->toggle_end_cursor.par() ||
1081                                  lt->toggle_cursor.pos() != lt->toggle_end_cursor.pos());
1082         if (clear)
1083                 lt = 0;
1084         if (flag) {
1085                 updateLocal(bv, SELECTION, false);
1086         }
1087         showInsetCursor(bv);
1088 }
1089
1090
1091 Inset::RESULT InsetText::localDispatch(FuncRequest const & ev)
1092 {
1093         BufferView * bv = ev.view();
1094         switch (ev.action) {
1095                 case LFUN_MOUSE_PRESS:
1096                         lfunMousePress(ev);
1097                         return DISPATCHED;
1098                 case LFUN_MOUSE_MOTION:
1099                         lfunMouseMotion(ev);
1100                         return DISPATCHED;
1101                 case LFUN_MOUSE_RELEASE:
1102                         return lfunMouseRelease(ev) ? DISPATCHED : UNDISPATCHED;
1103                 default:
1104                         break;
1105         }
1106
1107         bool was_empty = (paragraphs.begin()->empty() &&
1108                           boost::next(paragraphs.begin()) == paragraphs.end());
1109         no_selection = false;
1110         RESULT result = UpdatableInset::localDispatch(ev);
1111         if (result != UNDISPATCHED)
1112                 return DISPATCHED;
1113
1114         result = DISPATCHED;
1115         if (ev.action < 0 && ev.argument.empty())
1116                 return FINISHED;
1117
1118         if (the_locking_inset) {
1119                 result = the_locking_inset->localDispatch(ev);
1120                 if (result == DISPATCHED_NOUPDATE)
1121                         return result;
1122                 else if (result == DISPATCHED) {
1123                         updateLocal(bv, CURSOR_PAR, false);
1124                         return result;
1125                 } else if (result >= FINISHED) {
1126                         switch (result) {
1127                         case FINISHED_RIGHT:
1128                                 moveRightIntern(bv, false, false);
1129                                 result = DISPATCHED;
1130                                 break;
1131                         case FINISHED_UP:
1132                                 if ((result = moveUp(bv)) >= FINISHED) {
1133                                         updateLocal(bv, CURSOR, false);
1134                                         bv->unlockInset(this);
1135                                 }
1136                                 break;
1137                         case FINISHED_DOWN:
1138                                 if ((result = moveDown(bv)) >= FINISHED) {
1139                                         updateLocal(bv, CURSOR, false);
1140                                         bv->unlockInset(this);
1141                                 }
1142                                 break;
1143                         default:
1144                                 result = DISPATCHED;
1145                                 break;
1146                         }
1147                         the_locking_inset = 0;
1148                         updateLocal(bv, CURSOR, false);
1149                         return result;
1150                 }
1151         }
1152         hideInsetCursor(bv);
1153         bool clear = false;
1154         if (!lt) {
1155                 lt = getLyXText(bv);
1156                 clear = true;
1157         }
1158         int updwhat = 0;
1159         int updflag = false;
1160
1161         // what type of update to do on a cursor movement
1162         int cursor_update = CURSOR;
1163
1164         if (lt->selection.set())
1165                 cursor_update = SELECTION;
1166
1167         switch (ev.action) {
1168
1169         // Normal chars
1170         case LFUN_SELFINSERT:
1171                 if (bv->buffer()->isReadonly()) {
1172 //          setErrorMessage(N_("Document is read only"));
1173                         break;
1174                 }
1175                 if (!ev.argument.empty()) {
1176                         /* Automatically delete the currently selected
1177                          * text and replace it with what is being
1178                          * typed in now. Depends on lyxrc settings
1179                          * "auto_region_delete", which defaults to
1180                          * true (on). */
1181 #if 0
1182                         // This should not be needed here and is also WRONG!
1183                         setUndo(bv, Undo::INSERT,
1184                                 lt->cursor.par(), lt->cursor.par()->next());
1185 #endif
1186                         bv->switchKeyMap();
1187                         if (lyxrc.auto_region_delete) {
1188                                 if (lt->selection.set()) {
1189                                         lt->cutSelection(false, false);
1190                                 }
1191                         }
1192                         lt->clearSelection();
1193                         for (string::size_type i = 0; i < ev.argument.length(); ++i) {
1194                                 bv->owner()->getIntl().getTransManager().
1195                                         TranslateAndInsert(ev.argument[i], lt);
1196                         }
1197                 }
1198                 lt->selection.cursor = lt->cursor;
1199                 updwhat = CURSOR | CURSOR_PAR;
1200                 updflag = true;
1201                 result = DISPATCHED_NOUPDATE;
1202                 break;
1203
1204         // cursor movements that need special handling
1205
1206         case LFUN_RIGHT:
1207                 result = moveRight(bv);
1208                 finishUndo();
1209                 updwhat = cursor_update;
1210                 break;
1211         case LFUN_LEFT:
1212                 finishUndo();
1213                 result = moveLeft(bv);
1214                 updwhat = cursor_update;
1215                 break;
1216         case LFUN_DOWN:
1217                 finishUndo();
1218                 result = moveDown(bv);
1219                 updwhat = cursor_update;
1220                 break;
1221         case LFUN_UP:
1222                 finishUndo();
1223                 result = moveUp(bv);
1224                 updwhat = cursor_update;
1225                 break;
1226
1227         case LFUN_PRIOR:
1228                 if (crow(bv) == lt->rows().begin())
1229                         result = FINISHED_UP;
1230                 else {
1231                         lt->cursorPrevious();
1232                         lt->clearSelection();
1233                         result = DISPATCHED_NOUPDATE;
1234                 }
1235                 updwhat = cursor_update;
1236                 break;
1237
1238         case LFUN_NEXT:
1239                 if (boost::next(crow(bv)) == lt->rows().end())
1240                         result = FINISHED_DOWN;
1241                 else {
1242                         lt->cursorNext();
1243                         lt->clearSelection();
1244                         result = DISPATCHED_NOUPDATE;
1245                 }
1246                 updwhat = cursor_update;
1247                 break;
1248
1249         case LFUN_BACKSPACE: {
1250                 if (lt->selection.set())
1251                         lt->cutSelection(true, false);
1252                 else
1253                         lt->backspace();
1254                 updwhat = CURSOR_PAR;
1255                 updflag = true;
1256                 break;
1257         }
1258
1259         case LFUN_DELETE: {
1260                 if (lt->selection.set()) {
1261                         lt->cutSelection(true, false);
1262                 } else {
1263                         lt->Delete();
1264                 }
1265                 updwhat = CURSOR_PAR;
1266                 updflag = true;
1267                 break;
1268         }
1269
1270         case LFUN_CUT: {
1271                 lt->cutSelection(bv);
1272                 updwhat = CURSOR_PAR;
1273                 updflag = true;
1274                 break;
1275         }
1276
1277         case LFUN_COPY:
1278                 finishUndo();
1279                 lt->copySelection();
1280                 updwhat = CURSOR_PAR;
1281                 break;
1282
1283         case LFUN_PASTESELECTION:
1284         {
1285                 string const clip(bv->getClipboard());
1286
1287                 if (clip.empty())
1288                         break;
1289                 if (ev.argument == "paragraph") {
1290                         lt->insertStringAsParagraphs(clip);
1291                 } else {
1292                         lt->insertStringAsLines(clip);
1293                 }
1294                 // bug 393
1295                 lt->clearSelection();
1296
1297                 updwhat = CURSOR_PAR;
1298                 updflag = true;
1299                 break;
1300         }
1301
1302         case LFUN_PASTE: {
1303                 if (!autoBreakRows) {
1304                         if (CutAndPaste::nrOfParagraphs() > 1) {
1305 #ifdef WITH_WARNINGS
1306 #warning FIXME horrendously bad UI
1307 #endif
1308                                 Alert::error(_("Paste failed"), _("Cannot include more than one paragraph."));
1309                                 break;
1310                         }
1311                 }
1312
1313                 lt->pasteSelection();
1314                 // bug 393
1315                 lt->clearSelection();
1316                 updwhat = CURSOR_PAR;
1317                 updflag = true;
1318                 break;
1319         }
1320
1321         case LFUN_BREAKPARAGRAPH:
1322                 if (!autoBreakRows) {
1323                         result = DISPATCHED;
1324                         break;
1325                 }
1326                 lt->breakParagraph(paragraphs, 0);
1327                 updwhat = CURSOR | FULL;
1328                 updflag = true;
1329                 break;
1330
1331         case LFUN_BREAKPARAGRAPHKEEPLAYOUT:
1332                 if (!autoBreakRows) {
1333                         result = DISPATCHED;
1334                         break;
1335                 }
1336                 lt->breakParagraph(paragraphs, 1);
1337                 updwhat = CURSOR | FULL;
1338                 updflag = true;
1339                 break;
1340
1341         case LFUN_BREAKLINE: {
1342                 if (!autoBreakRows) {
1343                         result = DISPATCHED;
1344                         break;
1345                 }
1346
1347                 lt->insertInset(new InsetNewline);
1348                 updwhat = CURSOR | CURSOR_PAR;
1349                 updflag = true;
1350                 break;
1351         }
1352
1353         case LFUN_LAYOUT:
1354                 // do not set layouts on non breakable textinsets
1355                 if (autoBreakRows) {
1356                         string cur_layout = cpar(bv)->layout()->name();
1357
1358                         // Derive layout number from given argument (string)
1359                         // and current buffer's textclass (number). */
1360                         LyXTextClass const & tclass =
1361                                 bv->buffer()->params.getLyXTextClass();
1362                         string layout = ev.argument;
1363                         bool hasLayout = tclass.hasLayout(layout);
1364
1365                         // If the entry is obsolete, use the new one instead.
1366                         if (hasLayout) {
1367                                 string const & obs =
1368                                         tclass[layout]->obsoleted_by();
1369                                 if (!obs.empty())
1370                                         layout = obs;
1371                         }
1372
1373                         // see if we found the layout number:
1374                         if (!hasLayout) {
1375                                 FuncRequest lf(LFUN_MESSAGE, N_("Layout ") + ev.argument + N_(" not known"));
1376                                 bv->owner()->dispatch(lf);
1377                                 break;
1378                         }
1379
1380                         if (cur_layout != layout) {
1381                                 cur_layout = layout;
1382                                 lt->setLayout(layout);
1383                                 bv->owner()->setLayout(cpar(bv)->layout()->name());
1384                                 updwhat = CURSOR_PAR;
1385                                 updflag = true;
1386                         }
1387                 } else {
1388                         // reset the layout box
1389                         bv->owner()->setLayout(cpar(bv)->layout()->name());
1390                 }
1391                 break;
1392         case LFUN_PARAGRAPH_SPACING:
1393                 // This one is absolutely not working. When fiddling with this
1394                 // it also seems to me that the paragraphs inside the insettext
1395                 // inherit bufferparams/paragraphparams in a strange way. (Lgb)
1396                 // FIXME: how old is this comment ? ...
1397         {
1398                 Paragraph * par = lt->cursor.par();
1399                 Spacing::Space cur_spacing = par->params().spacing().getSpace();
1400                 float cur_value = 1.0;
1401                 if (cur_spacing == Spacing::Other) {
1402                         cur_value = par->params().spacing().getValue();
1403                 }
1404
1405                 istringstream istr(ev.argument.c_str());
1406                 string tmp;
1407                 istr >> tmp;
1408                 Spacing::Space new_spacing = cur_spacing;
1409                 float new_value = cur_value;
1410                 if (tmp.empty()) {
1411                         lyxerr << "Missing argument to `paragraph-spacing'"
1412                                    << endl;
1413                 } else if (tmp == "single") {
1414                         new_spacing = Spacing::Single;
1415                 } else if (tmp == "onehalf") {
1416                         new_spacing = Spacing::Onehalf;
1417                 } else if (tmp == "double") {
1418                         new_spacing = Spacing::Double;
1419                 } else if (tmp == "other") {
1420                         new_spacing = Spacing::Other;
1421                         float tmpval = 0.0;
1422                         istr >> tmpval;
1423                         lyxerr << "new_value = " << tmpval << endl;
1424                         if (tmpval != 0.0)
1425                                 new_value = tmpval;
1426                 } else if (tmp == "default") {
1427                         new_spacing = Spacing::Default;
1428                 } else {
1429                         lyxerr << _("Unknown spacing argument: ")
1430                                    << ev.argument << endl;
1431                 }
1432                 if (cur_spacing != new_spacing || cur_value != new_value) {
1433                         par->params().spacing(Spacing(new_spacing, new_value));
1434                         updwhat = CURSOR_PAR;
1435                         updflag = true;
1436                 }
1437         }
1438         break;
1439
1440         // These need to do repaints but don't require
1441         // special handling otherwise. A *lot* of the
1442         // above could probably be done similarly ...
1443
1444         case LFUN_HOME:
1445         case LFUN_END:
1446         case LFUN_WORDLEFT:
1447         case LFUN_WORDRIGHT:
1448         // these two are really unhandled ...
1449         case LFUN_ENDBUF:
1450         case LFUN_BEGINNINGBUF:
1451                 updwhat = cursor_update;
1452                 if (!bv->dispatch(ev))
1453                         result = UNDISPATCHED;
1454                 break;
1455
1456         case LFUN_RIGHTSEL:
1457         case LFUN_UPSEL:
1458         case LFUN_DOWNSEL:
1459         case LFUN_LEFTSEL:
1460         case LFUN_HOMESEL:
1461         case LFUN_ENDSEL:
1462         case LFUN_WORDLEFTSEL:
1463         case LFUN_WORDRIGHTSEL:
1464                 updwhat = SELECTION;
1465
1466                 // fallthrough
1467
1468         default:
1469                 if (!bv->dispatch(ev))
1470                         result = UNDISPATCHED;
1471                 break;
1472         }
1473
1474         if (clear)
1475                 lt = 0;
1476         if (updwhat > 0)
1477                 updateLocal(bv, updwhat, updflag);
1478         /// If the action has deleted all text in the inset, we need to change the
1479         // language to the language of the surronding text.
1480         if (!was_empty && paragraphs.begin()->empty() &&
1481             boost::next(paragraphs.begin()) == paragraphs.end()) {
1482                 LyXFont font(LyXFont::ALL_IGNORE);
1483                 font.setLanguage(bv->getParentLanguage(this));
1484                 setFont(bv, font, false);
1485         }
1486
1487         if (result >= FINISHED)
1488                 bv->unlockInset(this);
1489
1490         if (result == DISPATCHED_NOUPDATE && (need_update & FULL))
1491                 result = DISPATCHED;
1492         return result;
1493 }
1494
1495
1496 int InsetText::latex(Buffer const * buf, ostream & os,
1497                      bool moving_arg, bool) const
1498 {
1499         TexRow texrow;
1500         latexParagraphs(buf, paragraphs,
1501                         paragraphs.begin(), paragraphs.end(),
1502                         os, texrow, moving_arg);
1503         return texrow.rows();
1504 }
1505
1506
1507 int InsetText::ascii(Buffer const * buf, ostream & os, int linelen) const
1508 {
1509         unsigned int lines = 0;
1510
1511         ParagraphList::iterator beg = paragraphs.begin();
1512         ParagraphList::iterator end = paragraphs.end();
1513         ParagraphList::iterator it = beg;
1514         for (; it != end; ++it) {
1515                 string const tmp = buf->asciiParagraph(*it, linelen, it == beg);
1516                 lines += lyx::count(tmp.begin(), tmp.end(), '\n');
1517                 os << tmp;
1518         }
1519         return lines;
1520 }
1521
1522
1523 int InsetText::docbook(Buffer const * buf, ostream & os, bool mixcont) const
1524 {
1525         unsigned int lines = 0;
1526
1527         vector<string> environment_stack(10);
1528         vector<string> environment_inner(10);
1529
1530         int const command_depth = 0;
1531         string item_name;
1532
1533         Paragraph::depth_type depth = 0; // paragraph depth
1534
1535         ParagraphList::iterator pit = paragraphs.begin();
1536         ParagraphList::iterator pend = paragraphs.end();
1537
1538         for (; pit != pend; ++pit) {
1539                 string sgmlparam;
1540                 int desc_on = 0; // description mode
1541
1542                 LyXLayout_ptr const & style = pit->layout();
1543
1544                 // environment tag closing
1545                 for (; depth > pit->params().depth(); --depth) {
1546                         if (environment_inner[depth] != "!-- --") {
1547                                 item_name = "listitem";
1548                                 lines += sgml::closeTag(os, command_depth + depth, mixcont, item_name);
1549                                 if (environment_inner[depth] == "varlistentry")
1550                                         lines += sgml::closeTag(os, depth+command_depth, mixcont, environment_inner[depth]);
1551                         }
1552                         lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_stack[depth]);
1553                         environment_stack[depth].erase();
1554                         environment_inner[depth].erase();
1555                 }
1556
1557                 if (depth == pit->params().depth()
1558                    && environment_stack[depth] != style->latexname()
1559                    && !environment_stack[depth].empty()) {
1560                         if (environment_inner[depth] != "!-- --") {
1561                                 item_name= "listitem";
1562                                 lines += sgml::closeTag(os, command_depth+depth, mixcont, item_name);
1563                                 if (environment_inner[depth] == "varlistentry")
1564                                         lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_inner[depth]);
1565                         }
1566
1567                         lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_stack[depth]);
1568
1569                         environment_stack[depth].erase();
1570                         environment_inner[depth].erase();
1571                 }
1572
1573                 // Write opening SGML tags.
1574                 switch (style->latextype) {
1575                 case LATEX_PARAGRAPH:
1576                         lines += sgml::openTag(os, depth + command_depth, mixcont, style->latexname());
1577                         break;
1578
1579                 case LATEX_COMMAND:
1580                         buf->sgmlError(&*pit, 0,  _("Error: LatexType Command not allowed here.\n"));
1581                         return -1;
1582                         break;
1583
1584                 case LATEX_ENVIRONMENT:
1585                 case LATEX_ITEM_ENVIRONMENT:
1586                         if (depth < pit->params().depth()) {
1587                                 depth = pit->params().depth();
1588                                 environment_stack[depth].erase();
1589                         }
1590
1591                         if (environment_stack[depth] != style->latexname()) {
1592                                 if (environment_stack.size() == depth + 1) {
1593                                         environment_stack.push_back("!-- --");
1594                                         environment_inner.push_back("!-- --");
1595                                 }
1596                                 environment_stack[depth] = style->latexname();
1597                                 environment_inner[depth] = "!-- --";
1598                                 lines += sgml::openTag(os, depth + command_depth, mixcont, environment_stack[depth]);
1599                         } else {
1600                                 if (environment_inner[depth] != "!-- --") {
1601                                         item_name= "listitem";
1602                                         lines += sgml::closeTag(os, command_depth + depth, mixcont, item_name);
1603                                         if (environment_inner[depth] == "varlistentry")
1604                                                 lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_inner[depth]);
1605                                 }
1606                         }
1607
1608                         if (style->latextype == LATEX_ENVIRONMENT) {
1609                                 if (!style->latexparam().empty()) {
1610                                         if (style->latexparam() == "CDATA")
1611                                                 os << "<![CDATA[";
1612                                         else
1613                                           lines += sgml::openTag(os, depth + command_depth, mixcont, style->latexparam());
1614                                 }
1615                                 break;
1616                         }
1617
1618                         desc_on = (style->labeltype == LABEL_MANUAL);
1619
1620                         environment_inner[depth] = desc_on ? "varlistentry" : "listitem";
1621                         lines += sgml::openTag(os, depth + 1 + command_depth, mixcont, environment_inner[depth]);
1622
1623                         item_name = desc_on ? "term" : "para";
1624                         lines += sgml::openTag(os, depth + 1 + command_depth, mixcont, item_name);
1625
1626                         break;
1627                 default:
1628                         lines += sgml::openTag(os, depth + command_depth, mixcont, style->latexname());
1629                         break;
1630                 }
1631
1632                 buf->simpleDocBookOnePar(os, &*pit, desc_on, depth + 1 + command_depth);
1633
1634                 string end_tag;
1635                 // write closing SGML tags
1636                 switch (style->latextype) {
1637                 case LATEX_ENVIRONMENT:
1638                         if (!style->latexparam().empty()) {
1639                                 if (style->latexparam() == "CDATA")
1640                                         os << "]]>";
1641                                 else
1642                                         lines += sgml::closeTag(os, depth + command_depth, mixcont, style->latexparam());
1643                         }
1644                         break;
1645                 case LATEX_ITEM_ENVIRONMENT:
1646                         if (desc_on == 1) break;
1647                         end_tag= "para";
1648                         lines += sgml::closeTag(os, depth + 1 + command_depth, mixcont, end_tag);
1649                         break;
1650                 case LATEX_PARAGRAPH:
1651                         lines += sgml::closeTag(os, depth + command_depth, mixcont, style->latexname());
1652                         break;
1653                 default:
1654                         lines += sgml::closeTag(os, depth + command_depth, mixcont, style->latexname());
1655                         break;
1656                 }
1657         }
1658
1659         // Close open tags
1660         for (int d = depth; d >= 0; --d) {
1661                 if (!environment_stack[depth].empty()) {
1662                         if (environment_inner[depth] != "!-- --") {
1663                                 item_name = "listitem";
1664                                 lines += sgml::closeTag(os, command_depth + depth, mixcont, item_name);
1665                                if (environment_inner[depth] == "varlistentry")
1666                                        lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_inner[depth]);
1667                         }
1668
1669                         lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_stack[depth]);
1670                 }
1671         }
1672
1673         return lines;
1674 }
1675
1676
1677 void InsetText::validate(LaTeXFeatures & features) const
1678 {
1679         for_each(paragraphs.begin(), paragraphs.end(),
1680                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1681 }
1682
1683
1684 void InsetText::getCursorPos(BufferView * bv, int & x, int & y) const
1685 {
1686         if (the_locking_inset) {
1687                 the_locking_inset->getCursorPos(bv, x, y);
1688                 return;
1689         }
1690         x = cx(bv) - top_x - TEXT_TO_INSET_OFFSET;
1691         y = cy(bv) - TEXT_TO_INSET_OFFSET;
1692 }
1693
1694
1695 int InsetText::insetInInsetY() const
1696 {
1697         if (!the_locking_inset)
1698                 return 0;
1699
1700         return (inset_y + the_locking_inset->insetInInsetY());
1701 }
1702
1703
1704 void InsetText::toggleInsetCursor(BufferView * bv)
1705 {
1706         if (the_locking_inset) {
1707                 the_locking_inset->toggleInsetCursor(bv);
1708                 return;
1709         }
1710
1711         LyXFont const font(getLyXText(bv)->getFont(bv->buffer(), cpar(bv), cpos(bv)));
1712
1713         int const asc = font_metrics::maxAscent(font);
1714         int const desc = font_metrics::maxDescent(font);
1715
1716         if (isCursorVisible())
1717                 bv->hideLockedInsetCursor();
1718         else
1719                 bv->showLockedInsetCursor(cx(bv), cy(bv), asc, desc);
1720         toggleCursorVisible();
1721 }
1722
1723
1724 void InsetText::showInsetCursor(BufferView * bv, bool show)
1725 {
1726         if (the_locking_inset) {
1727                 the_locking_inset->showInsetCursor(bv, show);
1728                 return;
1729         }
1730         if (!isCursorVisible()) {
1731                 LyXFont const font =
1732                         getLyXText(bv)->getFont(bv->buffer(), cpar(bv), cpos(bv));
1733
1734                 int const asc = font_metrics::maxAscent(font);
1735                 int const desc = font_metrics::maxDescent(font);
1736
1737                 bv->fitLockedInsetCursor(cx(bv), cy(bv), asc, desc);
1738                 if (show)
1739                         bv->showLockedInsetCursor(cx(bv), cy(bv), asc, desc);
1740                 setCursorVisible(true);
1741         }
1742 }
1743
1744
1745 void InsetText::hideInsetCursor(BufferView * bv)
1746 {
1747         if (isCursorVisible()) {
1748                 bv->hideLockedInsetCursor();
1749                 setCursorVisible(false);
1750         }
1751         if (the_locking_inset)
1752                 the_locking_inset->hideInsetCursor(bv);
1753 }
1754
1755
1756 void InsetText::fitInsetCursor(BufferView * bv) const
1757 {
1758         if (the_locking_inset) {
1759                 the_locking_inset->fitInsetCursor(bv);
1760                 return;
1761         }
1762         LyXFont const font =
1763                 getLyXText(bv)->getFont(bv->buffer(), cpar(bv), cpos(bv));
1764
1765         int const asc = font_metrics::maxAscent(font);
1766         int const desc = font_metrics::maxDescent(font);
1767
1768         if (bv->fitLockedInsetCursor(cx(bv), cy(bv), asc, desc))
1769                 need_update |= FULL;
1770 }
1771
1772
1773 Inset::RESULT
1774 InsetText::moveRight(BufferView * bv, bool activate_inset, bool selecting)
1775 {
1776         if (getLyXText(bv)->cursor.par()->isRightToLeftPar(bv->buffer()->params))
1777                 return moveLeftIntern(bv, false, activate_inset, selecting);
1778         else
1779                 return moveRightIntern(bv, true, activate_inset, selecting);
1780 }
1781
1782
1783 Inset::RESULT
1784 InsetText::moveLeft(BufferView * bv, bool activate_inset, bool selecting)
1785 {
1786         if (getLyXText(bv)->cursor.par()->isRightToLeftPar(bv->buffer()->params))
1787                 return moveRightIntern(bv, true, activate_inset, selecting);
1788         else
1789                 return moveLeftIntern(bv, false, activate_inset, selecting);
1790 }
1791
1792
1793 Inset::RESULT
1794 InsetText::moveRightIntern(BufferView * bv, bool front,
1795                            bool activate_inset, bool selecting)
1796 {
1797         if (!cpar(bv)->next() && (cpos(bv) >= cpar(bv)->size()))
1798                 return FINISHED_RIGHT;
1799         if (activate_inset && checkAndActivateInset(bv, front))
1800                 return DISPATCHED;
1801         getLyXText(bv)->cursorRight(bv);
1802         if (!selecting)
1803                 getLyXText(bv)->clearSelection();
1804         return DISPATCHED_NOUPDATE;
1805 }
1806
1807
1808 Inset::RESULT
1809 InsetText::moveLeftIntern(BufferView * bv, bool front,
1810                           bool activate_inset, bool selecting)
1811 {
1812         if (!cpar(bv)->previous() && (cpos(bv) <= 0))
1813                 return FINISHED;
1814         getLyXText(bv)->cursorLeft(bv);
1815         if (!selecting)
1816                 getLyXText(bv)->clearSelection();
1817         if (activate_inset && checkAndActivateInset(bv, front))
1818                 return DISPATCHED;
1819         return DISPATCHED_NOUPDATE;
1820 }
1821
1822
1823 Inset::RESULT InsetText::moveUp(BufferView * bv)
1824 {
1825         if (crow(bv) == getLyXText(bv)->rows().begin())
1826                 return FINISHED_UP;
1827         getLyXText(bv)->cursorUp(bv);
1828         getLyXText(bv)->clearSelection();
1829         return DISPATCHED_NOUPDATE;
1830 }
1831
1832
1833 Inset::RESULT InsetText::moveDown(BufferView * bv)
1834 {
1835         if (boost::next(crow(bv)) == getLyXText(bv)->rows().end())
1836                 return FINISHED_DOWN;
1837         getLyXText(bv)->cursorDown(bv);
1838         getLyXText(bv)->clearSelection();
1839         return DISPATCHED_NOUPDATE;
1840 }
1841
1842
1843 bool InsetText::insertInset(BufferView * bv, Inset * inset)
1844 {
1845         if (the_locking_inset) {
1846                 if (the_locking_inset->insetAllowed(inset))
1847                         return the_locking_inset->insertInset(bv, inset);
1848                 return false;
1849         }
1850         inset->setOwner(this);
1851         hideInsetCursor(bv);
1852         getLyXText(bv)->insertInset(inset);
1853         bv->fitCursor();
1854         updateLocal(bv, CURSOR_PAR|CURSOR, true);
1855         return true;
1856 }
1857
1858
1859 bool InsetText::insetAllowed(Inset::Code code) const
1860 {
1861         // in_insetAllowed is a really gross hack,
1862         // to allow us to call the owner's insetAllowed
1863         // without stack overflow, which can happen
1864         // when the owner uses InsetCollapsable::insetAllowed()
1865         bool ret = true;
1866         if (in_insetAllowed)
1867                 return ret;
1868         in_insetAllowed = true;
1869         if (the_locking_inset)
1870                 ret = the_locking_inset->insetAllowed(code);
1871         else if (owner())
1872                 ret = owner()->insetAllowed(code);
1873         in_insetAllowed = false;
1874         return ret;
1875 }
1876
1877
1878 UpdatableInset * InsetText::getLockingInset() const
1879 {
1880         return the_locking_inset ? the_locking_inset->getLockingInset() :
1881                 const_cast<InsetText *>(this);
1882 }
1883
1884
1885 UpdatableInset * InsetText::getFirstLockingInsetOfType(Inset::Code c)
1886 {
1887         if (c == lyxCode())
1888                 return this;
1889         if (the_locking_inset)
1890                 return the_locking_inset->getFirstLockingInsetOfType(c);
1891         return 0;
1892 }
1893
1894
1895 bool InsetText::showInsetDialog(BufferView * bv) const
1896 {
1897         if (the_locking_inset)
1898                 return the_locking_inset->showInsetDialog(bv);
1899         return false;
1900 }
1901
1902
1903 vector<string> const InsetText::getLabelList() const
1904 {
1905         vector<string> label_list;
1906
1907         ParagraphList::iterator pit = paragraphs.begin();
1908         ParagraphList::iterator pend = paragraphs.end();
1909         for (; pit != pend; ++pit) {
1910                 InsetList::iterator beg = pit->insetlist.begin();
1911                 InsetList::iterator end = pit->insetlist.end();
1912                 for (; beg != end; ++beg) {
1913                         vector<string> const l = beg.getInset()->getLabelList();
1914                         label_list.insert(label_list.end(), l.begin(), l.end());
1915                 }
1916         }
1917         return label_list;
1918 }
1919
1920
1921 void InsetText::setFont(BufferView * bv, LyXFont const & font, bool toggleall,
1922                         bool selectall)
1923 {
1924         if (the_locking_inset) {
1925                 the_locking_inset->setFont(bv, font, toggleall, selectall);
1926                 return;
1927         }
1928         if ((boost::next(paragraphs.begin()) == paragraphs.end() &&
1929              paragraphs.begin()->empty()) || cpar(bv)->empty()) {
1930                 getLyXText(bv)->setFont(font, toggleall);
1931                 return;
1932         }
1933         bool clear = false;
1934         if (!lt) {
1935                 lt = getLyXText(bv);
1936                 clear = true;
1937         }
1938         if (lt->selection.set()) {
1939                 setUndo(bv, Undo::EDIT, lt->cursor.par(), lt->cursor.par()->next());
1940         }
1941         if (selectall)
1942                 selectAll(bv);
1943         lt->toggleFree(font, toggleall);
1944         if (selectall)
1945                 lt->clearSelection();
1946         bv->fitCursor();
1947         bool flag = (selectall || lt->selection.set());
1948         if (clear)
1949                 lt = 0;
1950         if (flag)
1951                 updateLocal(bv, FULL, true);
1952         else
1953                 updateLocal(bv, CURSOR_PAR, true);
1954 }
1955
1956
1957 bool InsetText::checkAndActivateInset(BufferView * bv, bool front)
1958 {
1959         if (cpar(bv)->isInset(cpos(bv))) {
1960                 Inset * inset =
1961                         static_cast<UpdatableInset*>(cpar(bv)->getInset(cpos(bv)));
1962                 if (!isHighlyEditableInset(inset))
1963                         return false;
1964                 inset->edit(bv, front);
1965                 if (!the_locking_inset)
1966                         return false;
1967                 updateLocal(bv, CURSOR, false);
1968                 return true;
1969         }
1970         return false;
1971 }
1972
1973
1974 bool InsetText::checkAndActivateInset(BufferView * bv, int x, int y,
1975                                       mouse_button::state button)
1976 {
1977         x -= drawTextXOffset;
1978         int dummyx = x;
1979         int dummyy = y + insetAscent;
1980         Inset * inset = getLyXText(bv)->checkInsetHit(dummyx, dummyy);
1981         // we only do the edit() call if the inset was hit by the mouse
1982         // or if it is a highly editable inset. So we should call this
1983         // function from our own edit with button < 0.
1984         // FIXME: GUII jbl. I've changed this to ::none for now which is probably
1985         // WRONG
1986         if (button == mouse_button::none && !isHighlyEditableInset(inset))
1987                 return false;
1988
1989         if (inset) {
1990                 if (x < 0)
1991                         x = insetWidth;
1992                 if (y < 0)
1993                         y = insetDescent;
1994                 inset_x = cix(bv) - top_x + drawTextXOffset;
1995                 inset_y = ciy(bv) + drawTextYOffset;
1996                 inset->edit(bv, x - inset_x, y - inset_y, button);
1997                 if (!the_locking_inset)
1998                         return false;
1999                 updateLocal(bv, CURSOR, false);
2000                 return true;
2001         }
2002         return false;
2003 }
2004
2005
2006 int InsetText::getMaxWidth(BufferView * bv, UpdatableInset const * inset) const
2007 {
2008 #if 0
2009         int w = UpdatableInset::getMaxWidth(bv, inset);
2010         if (w < 0) {
2011                 return -1;
2012         }
2013         if (owner()) {
2014                 w = w - top_x + owner()->x();
2015                 return w;
2016         }
2017         w -= (2 * TEXT_TO_INSET_OFFSET);
2018         return w - top_x;
2019 #else
2020         return UpdatableInset::getMaxWidth(bv, inset);
2021 #endif
2022 }
2023
2024
2025 void InsetText::setParagraphData(Paragraph * p, bool same_id)
2026 {
2027         // we have to unlock any locked inset otherwise we're in troubles
2028         the_locking_inset = 0;
2029
2030         paragraphs.clear();
2031         paragraphs.set(new Paragraph(*p, same_id));
2032         paragraphs.begin()->setInsetOwner(this);
2033         Paragraph * np = &*(paragraphs.begin());
2034         while (p->next()) {
2035                 p = p->next();
2036                 np->next(new Paragraph(*p, same_id));
2037                 np->next()->previous(np);
2038                 np = np->next();
2039                 np->setInsetOwner(this);
2040         }
2041         reinitLyXText();
2042         need_update = INIT;
2043 }
2044
2045
2046 void InsetText::markNew(bool track_changes)
2047 {
2048         ParagraphList::iterator pit = paragraphs.begin();
2049         ParagraphList::iterator pend = paragraphs.end();
2050         for (; pit != pend; ++pit) {
2051                 if (track_changes) {
2052                         pit->trackChanges();
2053                 } else {
2054                         // no-op when not tracking
2055                         pit->cleanChanges();
2056                 }
2057         }
2058 }
2059
2060
2061 void InsetText::setText(string const & data, LyXFont const & font)
2062 {
2063         clear(false);
2064         for (unsigned int i = 0; i < data.length(); ++i)
2065                 paragraphs.begin()->insertChar(i, data[i], font);
2066         reinitLyXText();
2067 }
2068
2069
2070 void InsetText::setAutoBreakRows(bool flag)
2071 {
2072         if (flag != autoBreakRows) {
2073                 autoBreakRows = flag;
2074                 if (!flag)
2075                         removeNewlines();
2076                 need_update = INIT;
2077         }
2078 }
2079
2080
2081 void InsetText::setDrawFrame(BufferView * bv, DrawFrame how)
2082 {
2083         if (how != drawFrame_) {
2084                 drawFrame_ = how;
2085                 if (bv)
2086                         updateLocal(bv, DRAW_FRAME, false);
2087         }
2088 }
2089
2090
2091 void InsetText::setFrameColor(BufferView * bv, LColor::color col)
2092 {
2093         if (frame_color != col) {
2094                 frame_color = col;
2095                 if (bv)
2096                         updateLocal(bv, DRAW_FRAME, false);
2097         }
2098 }
2099
2100
2101 int InsetText::cx(BufferView * bv) const
2102 {
2103         // we do nothing dangerous so we use a local cache
2104         LyXText * llt = getLyXText(bv);
2105         int x = llt->cursor.x() + top_x + TEXT_TO_INSET_OFFSET;
2106         if (the_locking_inset) {
2107                 LyXFont font = llt->getFont(bv->buffer(), llt->cursor.par(),
2108                                             llt->cursor.pos());
2109                 if (font.isVisibleRightToLeft())
2110                         x -= the_locking_inset->width(bv, font);
2111         }
2112         return x;
2113 }
2114
2115
2116 int InsetText::cix(BufferView * bv) const
2117 {
2118         // we do nothing dangerous so we use a local cache
2119         LyXText * llt = getLyXText(bv);
2120         int x = llt->cursor.ix() + top_x + TEXT_TO_INSET_OFFSET;
2121         if (the_locking_inset) {
2122                 LyXFont font = llt->getFont(bv->buffer(), llt->cursor.par(),
2123                                             llt->cursor.pos());
2124                 if (font.isVisibleRightToLeft())
2125                         x -= the_locking_inset->width(bv, font);
2126         }
2127         return x;
2128 }
2129
2130
2131 int InsetText::cy(BufferView * bv) const
2132 {
2133         LyXFont font;
2134         return getLyXText(bv)->cursor.y() - ascent(bv, font) + TEXT_TO_INSET_OFFSET;
2135 }
2136
2137
2138 int InsetText::ciy(BufferView * bv) const
2139 {
2140         LyXFont font;
2141         return getLyXText(bv)->cursor.iy() - ascent(bv, font) + TEXT_TO_INSET_OFFSET;
2142 }
2143
2144
2145 pos_type InsetText::cpos(BufferView * bv) const
2146 {
2147         return getLyXText(bv)->cursor.pos();
2148 }
2149
2150
2151 Paragraph * InsetText::cpar(BufferView * bv) const
2152 {
2153         return getLyXText(bv)->cursor.par();
2154 }
2155
2156
2157 bool InsetText::cboundary(BufferView * bv) const
2158 {
2159         return getLyXText(bv)->cursor.boundary();
2160 }
2161
2162
2163 RowList::iterator InsetText::crow(BufferView * bv) const
2164 {
2165         return getLyXText(bv)->cursor.row();
2166 }
2167
2168
2169 LyXText * InsetText::getLyXText(BufferView const * lbv,
2170                                 bool const recursive) const
2171 {
2172         if (cached_bview == lbv) {
2173                 if (recursive && the_locking_inset)
2174                         return the_locking_inset->getLyXText(lbv, true);
2175                 LyXText * lt = cached_text.get();
2176                 lyx::Assert(lt && lt->rows().begin()->par() == &*(paragraphs.begin()));
2177                 return lt;
2178         }
2179         // Super UGLY! (Lgb)
2180         BufferView * bv = const_cast<BufferView *>(lbv);
2181
2182         cached_bview = bv;
2183         Cache::iterator it = cache.find(bv);
2184
2185         if (it != cache.end()) {
2186                 if (do_reinit) {
2187                         reinitLyXText();
2188                 } else if (do_resize) {
2189                         resizeLyXText(do_resize);
2190                 } else {
2191                         if (lt || !it->second.remove) {
2192                                 lyx::Assert(it->second.text.get());
2193                                 cached_text = it->second.text;
2194                                 if (recursive && the_locking_inset) {
2195                                         return the_locking_inset->getLyXText(bv, true);
2196                                 }
2197                                 return cached_text.get();
2198                         } else if (it->second.remove) {
2199                                 if (locked) {
2200                                         saveLyXTextState(it->second.text.get());
2201                                 } else {
2202                                         sstate.lpar = 0;
2203                                 }
2204                         }
2205                         //
2206                         // when we have to reinit the existing LyXText!
2207                         //
2208                         it->second.text->init(bv);
2209                         restoreLyXTextState(it->second.text.get());
2210                         it->second.remove = false;
2211                 }
2212                 cached_text = it->second.text;
2213                 if (the_locking_inset && recursive) {
2214                         return the_locking_inset->getLyXText(bv);
2215                 }
2216                 return cached_text.get();
2217         }
2218         ///
2219         // we are here only if we don't have a BufferView * in the cache!!!
2220         ///
2221         cached_text.reset(new LyXText(bv, const_cast<InsetText *>(this)));
2222         cached_text->init(bv);
2223         restoreLyXTextState(cached_text.get());
2224
2225         cache.insert(make_pair(bv, cached_text));
2226
2227         if (the_locking_inset && recursive) {
2228                 return the_locking_inset->getLyXText(bv);
2229         }
2230         return cached_text.get();
2231 }
2232
2233
2234 void InsetText::deleteLyXText(BufferView * bv, bool recursive) const
2235 {
2236         cached_bview = 0;
2237
2238         Cache::iterator it = cache.find(bv);
2239
2240         if (it == cache.end()) {
2241                 return;
2242         }
2243
2244         lyx::Assert(it->second.text.get());
2245
2246         it->second.remove = true;
2247         if (recursive) {
2248                 /// then remove all LyXText in text-insets
2249                 for_each(paragraphs.begin(), paragraphs.end(),
2250                          boost::bind(&Paragraph::deleteInsetsLyXText, _1, bv));
2251         }
2252 }
2253
2254
2255 void InsetText::resizeLyXText(BufferView * bv, bool force) const
2256 {
2257         if (lt) {
2258                 // we cannot resize this because we are in use!
2259                 // so do this on the next possible getLyXText()
2260                 do_resize = bv;
2261                 return;
2262         }
2263         do_resize = 0;
2264         if (boost::next(paragraphs.begin()) == paragraphs.end() &&
2265             paragraphs.begin()->empty()) { // no data, resize not neccessary!
2266                 // we have to do this as a fixed width may have changed!
2267                 LyXText * t = getLyXText(bv);
2268                 saveLyXTextState(t);
2269                 t->init(bv, true);
2270                 restoreLyXTextState(t);
2271                 return;
2272         }
2273         // one endless line, resize normally not necessary
2274         if (!force && getMaxWidth(bv, this) < 0)
2275                 return;
2276
2277         Cache::iterator it = cache.find(bv);
2278         if (it == cache.end()) {
2279                 return;
2280         }
2281         lyx::Assert(it->second.text.get());
2282
2283         LyXText * t = it->second.text.get();
2284         saveLyXTextState(t);
2285
2286         for_each(paragraphs.begin(), paragraphs.end(),
2287                  boost::bind(&Paragraph::resizeInsetsLyXText, _1, bv));
2288
2289         t->init(bv, true);
2290         restoreLyXTextState(t);
2291         if (the_locking_inset) {
2292                 inset_x = cix(bv) - top_x + drawTextXOffset;
2293                 inset_y = ciy(bv) + drawTextYOffset;
2294         }
2295
2296         t->top_y(bv->screen().topCursorVisible(t->cursor, t->top_y()));
2297         if (!owner()) {
2298                 const_cast<InsetText*>(this)->updateLocal(bv, FULL, false);
2299                 // this will scroll the screen such that the cursor becomes visible
2300                 bv->updateScrollbar();
2301         } else {
2302                 need_update |= FULL;
2303         }
2304 }
2305
2306
2307 void InsetText::reinitLyXText() const
2308 {
2309         if (lt) {
2310                 // we cannot resize this because we are in use!
2311                 // so do this on the next possible getLyXText()
2312                 do_reinit = true;
2313                 return;
2314         }
2315         do_reinit = false;
2316         do_resize = 0;
2317         for (Cache::iterator it = cache.begin(); it != cache.end(); ++it) {
2318                 lyx::Assert(it->second.text.get());
2319
2320                 LyXText * t = it->second.text.get();
2321                 BufferView * bv = it->first;
2322
2323                 saveLyXTextState(t);
2324
2325                 for_each(paragraphs.begin(), paragraphs.end(),
2326                          boost::bind(&Paragraph::resizeInsetsLyXText, _1, bv));
2327
2328                 t->init(bv, true);
2329                 restoreLyXTextState(t);
2330                 if (the_locking_inset) {
2331                         inset_x = cix(bv) - top_x + drawTextXOffset;
2332                         inset_y = ciy(bv) + drawTextYOffset;
2333                 }
2334                 t->top_y(bv->screen().topCursorVisible(t->cursor, t->top_y()));
2335                 if (!owner()) {
2336                         const_cast<InsetText*>(this)->updateLocal(bv, FULL, false);
2337                         // this will scroll the screen such that the cursor becomes visible
2338                         bv->updateScrollbar();
2339                 } else {
2340                         need_update = FULL;
2341                 }
2342         }
2343 }
2344
2345
2346 void InsetText::removeNewlines()
2347 {
2348         bool changed = false;
2349
2350         ParagraphList::iterator it = paragraphs.begin();
2351         ParagraphList::iterator end = paragraphs.end();
2352         for (; it != end; ++it) {
2353                 for (int i = 0; i < it->size(); ++i) {
2354                         if (it->isNewline(i)) {
2355                                 changed = true;
2356                                 it->erase(i);
2357                         }
2358                 }
2359         }
2360         if (changed)
2361                 reinitLyXText();
2362 }
2363
2364
2365 bool InsetText::nodraw() const
2366 {
2367         if (the_locking_inset)
2368                 return the_locking_inset->nodraw();
2369         return UpdatableInset::nodraw();
2370 }
2371
2372
2373 int InsetText::scroll(bool recursive) const
2374 {
2375         int sx = UpdatableInset::scroll(false);
2376
2377         if (recursive && the_locking_inset)
2378                 sx += the_locking_inset->scroll(recursive);
2379
2380         return sx;
2381 }
2382
2383
2384 void InsetText::selectAll(BufferView * bv)
2385 {
2386         getLyXText(bv)->cursorTop();
2387         getLyXText(bv)->selection.cursor = getLyXText(bv)->cursor;
2388         getLyXText(bv)->cursorBottom();
2389         getLyXText(bv)->setSelection();
2390 }
2391
2392
2393 void InsetText::clearSelection(BufferView * bv)
2394 {
2395         getLyXText(bv)->clearSelection();
2396 }
2397
2398
2399 void InsetText::clearInset(BufferView * bv, int start_x, int baseline) const
2400 {
2401         Painter & pain = bv->painter();
2402         int w = insetWidth;
2403         int h = insetAscent + insetDescent;
2404         int ty = baseline - insetAscent;
2405
2406         if (ty < 0) {
2407                 h += ty;
2408                 ty = 0;
2409         }
2410         if ((ty + h) > pain.paperHeight())
2411                 h = pain.paperHeight();
2412         if ((top_x + drawTextXOffset + w) > pain.paperWidth())
2413                 w = pain.paperWidth();
2414         pain.fillRectangle(start_x + 1, ty + 1, w - 3, h - 1, backgroundColor());
2415         need_update = FULL;
2416 }
2417
2418
2419 Paragraph * InsetText::firstParagraph() const
2420 {
2421         Paragraph * result;
2422         if (the_locking_inset)
2423                 if ((result = the_locking_inset->firstParagraph()))
2424                         return result;
2425         return &*(paragraphs.begin());
2426 }
2427
2428
2429 Paragraph * InsetText::getFirstParagraph(int i) const
2430 {
2431         return (i == 0) ? &*(paragraphs.begin()) : 0;
2432 }
2433
2434
2435 LyXCursor const & InsetText::cursor(BufferView * bv) const
2436 {
2437         if (the_locking_inset)
2438                 return the_locking_inset->cursor(bv);
2439         return getLyXText(bv)->cursor;
2440 }
2441
2442
2443 void InsetText::paragraph(Paragraph * p)
2444 {
2445         // GENERAL COMMENT: We don't have to free the old paragraphs as the
2446         // caller of this function has to take care of it. This IS important
2447         // as we could have to insert a paragraph before this one and just
2448         // link the actual to a new ones next and set it with this function
2449         // and are done!
2450         paragraphs.set(p);
2451         // set ourself as owner for all the paragraphs inserted!
2452         for_each(paragraphs.begin(), paragraphs.end(),
2453                  boost::bind(&Paragraph::setInsetOwner, _1, this));
2454
2455         reinitLyXText();
2456         // redraw myself when asked for
2457         need_update = INIT;
2458 }
2459
2460
2461 Inset * InsetText::getInsetFromID(int id_arg) const
2462 {
2463         if (id_arg == id())
2464                 return const_cast<InsetText *>(this);
2465
2466         ParagraphList::iterator pit = paragraphs.begin();
2467         ParagraphList::iterator pend = paragraphs.end();
2468         for (; pit != pend; ++pit) {
2469                 InsetList::iterator it = pit->insetlist.begin();
2470                 InsetList::iterator end = pit->insetlist.end();
2471                 for (; it != end; ++it) {
2472                         if (it.getInset()->id() == id_arg)
2473                                 return it.getInset();
2474                         Inset * in = it.getInset()->getInsetFromID(id_arg);
2475                         if (in)
2476                                 return in;
2477                 }
2478         }
2479         return 0;
2480 }
2481
2482
2483 WordLangTuple const
2484 InsetText::selectNextWordToSpellcheck(BufferView * bv,
2485                                       float & value) const
2486 {
2487         bool clear = false;
2488         WordLangTuple word;
2489
2490         if (!lt) {
2491                 lt = getLyXText(bv);
2492                 clear = true;
2493         }
2494         if (the_locking_inset) {
2495                 word = the_locking_inset->selectNextWordToSpellcheck(bv, value);
2496                 if (!word.word().empty()) {
2497                         value += cy(bv);
2498                         if (clear)
2499                                 lt = 0;
2500                         return word;
2501                 }
2502                 // we have to go on checking so move cursor to the next char
2503                 lt->cursor.pos(lt->cursor.pos() + 1);
2504         }
2505         word = lt->selectNextWordToSpellcheck(value);
2506         if (word.word().empty())
2507                 bv->unlockInset(const_cast<InsetText *>(this));
2508         else
2509                 value = cy(bv);
2510         if (clear)
2511                 lt = 0;
2512         return word;
2513 }
2514
2515
2516 void InsetText::selectSelectedWord(BufferView * bv)
2517 {
2518         if (the_locking_inset) {
2519                 the_locking_inset->selectSelectedWord(bv);
2520                 return;
2521         }
2522         getLyXText(bv)->selectSelectedWord();
2523         updateLocal(bv, SELECTION, false);
2524 }
2525
2526
2527 void InsetText::toggleSelection(BufferView * bv, bool kill_selection)
2528 {
2529         if (the_locking_inset) {
2530                 the_locking_inset->toggleSelection(bv, kill_selection);
2531         }
2532         bool clear = false;
2533         if (!lt) {
2534                 lt = getLyXText(bv);
2535                 clear = true;
2536         }
2537
2538         int x = top_x + TEXT_TO_INSET_OFFSET;
2539
2540         RowList::iterator rowit = lt->rows().begin();
2541         RowList::iterator end = lt->rows().end();
2542         int y_offset = top_baseline - rowit->ascent_of_text();
2543         int y = y_offset;
2544         while ((rowit != end) && ((y + rowit->height()) <= 0)) {
2545                 y += rowit->height();
2546                 ++rowit;
2547         }
2548         if (y_offset < 0)
2549                 y_offset = y;
2550
2551         if (need_update & SELECTION)
2552                 need_update = NONE;
2553         bv->screen().toggleSelection(lt, bv, kill_selection, y_offset, x);
2554         if (clear)
2555                 lt = 0;
2556 }
2557
2558
2559 bool InsetText::nextChange(BufferView * bv, lyx::pos_type & length)
2560 {
2561         bool clear = false;
2562         if (!lt) {
2563                 lt = getLyXText(bv);
2564                 clear = true;
2565         }
2566         if (the_locking_inset) {
2567                 if (the_locking_inset->nextChange(bv, length))
2568                         return true;
2569                 lt->cursorRight(true);
2570         }
2571         lyxfind::SearchResult result =
2572                 lyxfind::findNextChange(bv, lt, length);
2573
2574         if (result == lyxfind::SR_FOUND) {
2575                 LyXCursor cur = lt->cursor;
2576                 bv->unlockInset(bv->theLockingInset());
2577                 if (bv->lockInset(this))
2578                         locked = true;
2579                 lt->cursor = cur;
2580                 lt->setSelectionRange(length);
2581                 updateLocal(bv, SELECTION, false);
2582         }
2583         if (clear)
2584                 lt = 0;
2585         return result != lyxfind::SR_NOT_FOUND;
2586 }
2587
2588
2589 bool InsetText::searchForward(BufferView * bv, string const & str,
2590                               bool cs, bool mw)
2591 {
2592         bool clear = false;
2593         if (!lt) {
2594                 lt = getLyXText(bv);
2595                 clear = true;
2596         }
2597         if (the_locking_inset) {
2598                 if (the_locking_inset->searchForward(bv, str, cs, mw))
2599                         return true;
2600                 lt->cursorRight(true);
2601         }
2602         lyxfind::SearchResult result =
2603                 lyxfind::LyXFind(bv, lt, str, true, cs, mw);
2604
2605         if (result == lyxfind::SR_FOUND) {
2606                 LyXCursor cur = lt->cursor;
2607                 bv->unlockInset(bv->theLockingInset());
2608                 if (bv->lockInset(this))
2609                         locked = true;
2610                 lt->cursor = cur;
2611                 lt->setSelectionRange(str.length());
2612                 updateLocal(bv, SELECTION, false);
2613         }
2614         if (clear)
2615                 lt = 0;
2616         return (result != lyxfind::SR_NOT_FOUND);
2617 }
2618
2619 bool InsetText::searchBackward(BufferView * bv, string const & str,
2620                                bool cs, bool mw)
2621 {
2622         if (the_locking_inset) {
2623                 if (the_locking_inset->searchBackward(bv, str, cs, mw))
2624                         return true;
2625         }
2626         bool clear = false;
2627         if (!lt) {
2628                 lt = getLyXText(bv);
2629                 clear = true;
2630         }
2631         if (!locked) {
2632                 ParagraphList::iterator pit = paragraphs.begin();
2633                 ParagraphList::iterator pend = paragraphs.end();
2634
2635                 while (boost::next(pit) != pend)
2636                         ++pit;
2637
2638                 lt->setCursor(&*pit, pit->size());
2639         }
2640         lyxfind::SearchResult result =
2641                 lyxfind::LyXFind(bv, lt, str, false, cs, mw);
2642
2643         if (result == lyxfind::SR_FOUND) {
2644                 LyXCursor cur = lt->cursor;
2645                 bv->unlockInset(bv->theLockingInset());
2646                 if (bv->lockInset(this))
2647                         locked = true;
2648                 lt->cursor = cur;
2649                 lt->setSelectionRange(str.length());
2650                 updateLocal(bv, SELECTION, false);
2651         }
2652         if (clear)
2653                 lt = 0;
2654         return (result != lyxfind::SR_NOT_FOUND);
2655 }
2656
2657
2658 bool InsetText::checkInsertChar(LyXFont & font)
2659 {
2660         if (owner())
2661                 return owner()->checkInsertChar(font);
2662         return true;
2663 }
2664
2665
2666 void InsetText::collapseParagraphs(BufferView * bv)
2667 {
2668         LyXText * llt = getLyXText(bv);
2669
2670         while (boost::next(paragraphs.begin()) != paragraphs.end()) {
2671                 if (!paragraphs.begin()->empty() &&
2672                     !boost::next(paragraphs.begin())->empty() &&
2673                         !paragraphs.begin()->isSeparator(paragraphs.begin()->size() - 1))
2674                 {
2675                         paragraphs.begin()->insertChar(paragraphs.begin()->size(), ' ');
2676                 }
2677                 if (llt->selection.set()) {
2678                         if (llt->selection.start.par() == boost::next(paragraphs.begin())) {
2679                                 llt->selection.start.par(&*(paragraphs.begin()));
2680                                 llt->selection.start.pos(
2681                                         llt->selection.start.pos() + paragraphs.begin()->size());
2682                         }
2683                         if (llt->selection.end.par() == boost::next(paragraphs.begin())) {
2684                                 llt->selection.end.par(&*(paragraphs.begin()));
2685                                 llt->selection.end.pos(
2686                                         llt->selection.end.pos() + paragraphs.begin()->size());
2687                         }
2688                 }
2689                 mergeParagraph(bv->buffer()->params, paragraphs, paragraphs.begin());
2690         }
2691         reinitLyXText();
2692 }
2693
2694
2695 void InsetText::getDrawFont(LyXFont & font) const
2696 {
2697         if (!owner())
2698                 return;
2699         owner()->getDrawFont(font);
2700 }
2701
2702
2703 void InsetText::appendParagraphs(Buffer * buffer,
2704                                  Paragraph * newpar)
2705 {
2706         BufferParams const & bparams = buffer->params;
2707         Paragraph * buf;
2708         Paragraph * tmpbuf = newpar;
2709         Paragraph * lastbuffer = buf = new Paragraph(*tmpbuf, false);
2710         if (bparams.tracking_changes)
2711                 buf->cleanChanges();
2712
2713         while (tmpbuf->next()) {
2714                 tmpbuf = tmpbuf->next();
2715                 lastbuffer->next(new Paragraph(*tmpbuf, false));
2716                 lastbuffer->next()->previous(lastbuffer);
2717                 lastbuffer = lastbuffer->next();
2718                 if (bparams.tracking_changes)
2719                         lastbuffer->cleanChanges();
2720         }
2721         lastbuffer = &*(paragraphs.begin());
2722         while (lastbuffer->next())
2723                 lastbuffer = lastbuffer->next();
2724         if (!newpar->empty() && !lastbuffer->empty() &&
2725                 !lastbuffer->isSeparator(lastbuffer->size() - 1))
2726         {
2727                 lastbuffer->insertChar(lastbuffer->size(), ' ');
2728         }
2729
2730         // make the buf exactly the same layout than our last paragraph
2731         buf->makeSameLayout(lastbuffer);
2732
2733         // paste it!
2734         lastbuffer->next(buf);
2735         buf->previous(lastbuffer);
2736         mergeParagraph(buffer->params, paragraphs, lastbuffer);
2737
2738         reinitLyXText();
2739 }
2740
2741
2742 void InsetText::addPreview(grfx::PreviewLoader & loader) const
2743 {
2744         ParagraphList::iterator pit = paragraphs.begin();
2745         ParagraphList::iterator pend = paragraphs.end();
2746
2747         for (; pit != pend; ++pit) {
2748                 InsetList::iterator it  = pit->insetlist.begin();
2749                 InsetList::iterator end = pit->insetlist.end();
2750                 for (; it != end; ++it) {
2751                         it.getInset()->addPreview(loader);
2752                 }
2753         }
2754 }