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