]> git.lyx.org Git - features.git/blob - src/insets/insettext.C
add warning make controllers compile and remove some alomost unused functions, commen...
[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(new 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(new Paragraph);
221         paragraphs.begin()->setInsetOwner(this);
222         paragraphs.begin()->layout(old_layout);
223
224         reinitLyXText();
225         need_update = INIT;
226 }
227
228
229 Inset * InsetText::clone(Buffer const &, bool same_id) const
230 {
231         return new InsetText(*this, same_id);
232 }
233
234
235 void InsetText::write(Buffer const * buf, ostream & os) const
236 {
237         os << "Text\n";
238         writeParagraphData(buf, os);
239 }
240
241
242 void InsetText::writeParagraphData(Buffer const * buf, ostream & os) const
243 {
244         ParagraphList::iterator it = paragraphs.begin();
245         ParagraphList::iterator end = paragraphs.end();
246         Paragraph::depth_type dth = 0;
247         for (; it != end; ++it) {
248                 it->write(buf, os, buf->params, dth);
249         }
250 }
251
252
253 void InsetText::read(Buffer const * buf, LyXLex & lex)
254 {
255         string token;
256         Paragraph::depth_type depth = 0;
257
258         clear(false);
259
260         if (buf->params.tracking_changes)
261                 paragraphs.begin()->trackChanges();
262
263         // delete the initial paragraph
264         paragraphs.clear();
265         ParagraphList::iterator pit = paragraphs.begin();
266
267         while (lex.isOK()) {
268                 lex.nextToken();
269                 token = lex.getString();
270                 if (token.empty())
271                         continue;
272                 if (token == "\\end_inset") {
273                         break;
274                 }
275
276                 if (token == "\\the_end") {
277                         lex.printError("\\the_end read in inset! Error in document!");
278                         return;
279                 }
280
281                 // FIXME: ugly.
282                 const_cast<Buffer*>(buf)->readParagraph(lex, token, paragraphs, pit, depth);
283         }
284
285         pit = paragraphs.begin();
286         ParagraphList::iterator const end = paragraphs.end();
287         for (; pit != end; ++pit)
288                 pit->setInsetOwner(this);
289
290         if (token != "\\end_inset") {
291                 lex.printError("Missing \\end_inset at this point. "
292                                            "Read: `$$Token'");
293         }
294         need_update = FULL;
295 }
296
297
298 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,
1138                                 lt->cursor.par(), boost::next(lt->cursor.par()));
1139 #endif
1140                         bv->switchKeyMap();
1141                         if (lyxrc.auto_region_delete) {
1142                                 if (lt->selection.set()) {
1143                                         lt->cutSelection(false, false);
1144                                 }
1145                         }
1146                         lt->clearSelection();
1147                         for (string::size_type i = 0; i < cmd.argument.length(); ++i) {
1148                                 bv->owner()->getIntl().getTransManager().
1149                                         TranslateAndInsert(cmd.argument[i], lt);
1150                         }
1151                 }
1152                 lt->selection.cursor = lt->cursor;
1153                 updwhat = CURSOR | CURSOR_PAR;
1154                 updflag = true;
1155                 result = DISPATCHED_NOUPDATE;
1156                 break;
1157
1158         // cursor movements that need special handling
1159
1160         case LFUN_RIGHT:
1161                 result = moveRight(bv);
1162                 finishUndo();
1163                 updwhat = cursor_update;
1164                 break;
1165         case LFUN_LEFT:
1166                 finishUndo();
1167                 result = moveLeft(bv);
1168                 updwhat = cursor_update;
1169                 break;
1170         case LFUN_DOWN:
1171                 finishUndo();
1172                 result = moveDown(bv);
1173                 updwhat = cursor_update;
1174                 break;
1175         case LFUN_UP:
1176                 finishUndo();
1177                 result = moveUp(bv);
1178                 updwhat = cursor_update;
1179                 break;
1180
1181         case LFUN_PRIOR:
1182                 if (crow(bv) == lt->rows().begin())
1183                         result = FINISHED_UP;
1184                 else {
1185                         lt->cursorPrevious();
1186                         lt->clearSelection();
1187                         result = DISPATCHED_NOUPDATE;
1188                 }
1189                 updwhat = cursor_update;
1190                 break;
1191
1192         case LFUN_NEXT:
1193                 if (boost::next(crow(bv)) == lt->rows().end())
1194                         result = FINISHED_DOWN;
1195                 else {
1196                         lt->cursorNext();
1197                         lt->clearSelection();
1198                         result = DISPATCHED_NOUPDATE;
1199                 }
1200                 updwhat = cursor_update;
1201                 break;
1202
1203         case LFUN_BACKSPACE: {
1204                 if (lt->selection.set())
1205                         lt->cutSelection(true, false);
1206                 else
1207                         lt->backspace();
1208                 updwhat = CURSOR_PAR;
1209                 updflag = true;
1210                 break;
1211         }
1212
1213         case LFUN_DELETE: {
1214                 if (lt->selection.set()) {
1215                         lt->cutSelection(true, false);
1216                 } else {
1217                         lt->Delete();
1218                 }
1219                 updwhat = CURSOR_PAR;
1220                 updflag = true;
1221                 break;
1222         }
1223
1224         case LFUN_CUT: {
1225                 lt->cutSelection(bv);
1226                 updwhat = CURSOR_PAR;
1227                 updflag = true;
1228                 break;
1229         }
1230
1231         case LFUN_COPY:
1232                 finishUndo();
1233                 lt->copySelection();
1234                 updwhat = CURSOR_PAR;
1235                 break;
1236
1237         case LFUN_PASTESELECTION:
1238         {
1239                 string const clip(bv->getClipboard());
1240
1241                 if (clip.empty())
1242                         break;
1243                 if (cmd.argument == "paragraph") {
1244                         lt->insertStringAsParagraphs(clip);
1245                 } else {
1246                         lt->insertStringAsLines(clip);
1247                 }
1248                 // bug 393
1249                 lt->clearSelection();
1250
1251                 updwhat = CURSOR_PAR;
1252                 updflag = true;
1253                 break;
1254         }
1255
1256         case LFUN_PASTE: {
1257                 if (!autoBreakRows) {
1258                         if (CutAndPaste::nrOfParagraphs() > 1) {
1259 #ifdef WITH_WARNINGS
1260 #warning FIXME horrendously bad UI
1261 #endif
1262                                 Alert::error(_("Paste failed"), _("Cannot include more than one paragraph."));
1263                                 break;
1264                         }
1265                 }
1266
1267                 lt->pasteSelection();
1268                 // bug 393
1269                 lt->clearSelection();
1270                 updwhat = CURSOR_PAR;
1271                 updflag = true;
1272                 break;
1273         }
1274
1275         case LFUN_BREAKPARAGRAPH:
1276                 if (!autoBreakRows) {
1277                         result = DISPATCHED;
1278                         break;
1279                 }
1280                 lt->breakParagraph(paragraphs, 0);
1281                 updwhat = CURSOR | FULL;
1282                 updflag = true;
1283                 break;
1284
1285         case LFUN_BREAKPARAGRAPHKEEPLAYOUT:
1286                 if (!autoBreakRows) {
1287                         result = DISPATCHED;
1288                         break;
1289                 }
1290                 lt->breakParagraph(paragraphs, 1);
1291                 updwhat = CURSOR | FULL;
1292                 updflag = true;
1293                 break;
1294
1295         case LFUN_BREAKLINE: {
1296                 if (!autoBreakRows) {
1297                         result = DISPATCHED;
1298                         break;
1299                 }
1300
1301                 lt->insertInset(new InsetNewline);
1302                 updwhat = CURSOR | CURSOR_PAR;
1303                 updflag = true;
1304                 break;
1305         }
1306
1307         case LFUN_LAYOUT:
1308                 // do not set layouts on non breakable textinsets
1309                 if (autoBreakRows) {
1310                         string cur_layout = cpar(bv)->layout()->name();
1311
1312                         // Derive layout number from given argument (string)
1313                         // and current buffer's textclass (number). */
1314                         LyXTextClass const & tclass =
1315                                 bv->buffer()->params.getLyXTextClass();
1316                         string layout = cmd.argument;
1317                         bool hasLayout = tclass.hasLayout(layout);
1318
1319                         // If the entry is obsolete, use the new one instead.
1320                         if (hasLayout) {
1321                                 string const & obs =
1322                                         tclass[layout]->obsoleted_by();
1323                                 if (!obs.empty())
1324                                         layout = obs;
1325                         }
1326
1327                         // see if we found the layout number:
1328                         if (!hasLayout) {
1329                                 FuncRequest lf(LFUN_MESSAGE, N_("Layout ") + cmd.argument + N_(" not known"));
1330                                 bv->owner()->dispatch(lf);
1331                                 break;
1332                         }
1333
1334                         if (cur_layout != layout) {
1335                                 cur_layout = layout;
1336                                 lt->setLayout(layout);
1337                                 bv->owner()->setLayout(cpar(bv)->layout()->name());
1338                                 updwhat = CURSOR_PAR;
1339                                 updflag = true;
1340                         }
1341                 } else {
1342                         // reset the layout box
1343                         bv->owner()->setLayout(cpar(bv)->layout()->name());
1344                 }
1345                 break;
1346         case LFUN_PARAGRAPH_SPACING:
1347                 // This one is absolutely not working. When fiddling with this
1348                 // it also seems to me that the paragraphs inside the insettext
1349                 // inherit bufferparams/paragraphparams in a strange way. (Lgb)
1350                 // FIXME: how old is this comment ? ...
1351         {
1352                 ParagraphList::iterator pit = lt->cursor.par();
1353                 Spacing::Space cur_spacing = pit->params().spacing().getSpace();
1354                 float cur_value = 1.0;
1355                 if (cur_spacing == Spacing::Other) {
1356                         cur_value = pit->params().spacing().getValue();
1357                 }
1358
1359                 istringstream istr(STRCONV(cmd.argument));
1360                 string tmp;
1361                 istr >> tmp;
1362                 Spacing::Space new_spacing = cur_spacing;
1363                 float new_value = cur_value;
1364                 if (tmp.empty()) {
1365                         lyxerr << "Missing argument to `paragraph-spacing'"
1366                                    << endl;
1367                 } else if (tmp == "single") {
1368                         new_spacing = Spacing::Single;
1369                 } else if (tmp == "onehalf") {
1370                         new_spacing = Spacing::Onehalf;
1371                 } else if (tmp == "double") {
1372                         new_spacing = Spacing::Double;
1373                 } else if (tmp == "other") {
1374                         new_spacing = Spacing::Other;
1375                         float tmpval = 0.0;
1376                         istr >> tmpval;
1377                         lyxerr << "new_value = " << tmpval << endl;
1378                         if (tmpval != 0.0)
1379                                 new_value = tmpval;
1380                 } else if (tmp == "default") {
1381                         new_spacing = Spacing::Default;
1382                 } else {
1383                         lyxerr << _("Unknown spacing argument: ")
1384                                    << cmd.argument << endl;
1385                 }
1386                 if (cur_spacing != new_spacing || cur_value != new_value) {
1387                         pit->params().spacing(Spacing(new_spacing, new_value));
1388                         updwhat = CURSOR_PAR;
1389                         updflag = true;
1390                 }
1391         }
1392         break;
1393
1394         // These need to do repaints but don't require
1395         // special handling otherwise. A *lot* of the
1396         // above could probably be done similarly ...
1397
1398         case LFUN_HOME:
1399         case LFUN_END:
1400         case LFUN_WORDLEFT:
1401         case LFUN_WORDRIGHT:
1402         // these two are really unhandled ...
1403         case LFUN_ENDBUF:
1404         case LFUN_BEGINNINGBUF:
1405                 updwhat = cursor_update;
1406                 if (!bv->dispatch(cmd))
1407                         result = UNDISPATCHED;
1408                 break;
1409
1410         case LFUN_RIGHTSEL:
1411         case LFUN_UPSEL:
1412         case LFUN_DOWNSEL:
1413         case LFUN_LEFTSEL:
1414         case LFUN_HOMESEL:
1415         case LFUN_ENDSEL:
1416         case LFUN_WORDLEFTSEL:
1417         case LFUN_WORDRIGHTSEL:
1418                 updwhat = SELECTION;
1419
1420                 // fallthrough
1421
1422         default:
1423                 if (!bv->dispatch(cmd))
1424                         result = UNDISPATCHED;
1425                 break;
1426         }
1427
1428         if (clear)
1429                 lt = 0;
1430         if (updwhat > 0)
1431                 updateLocal(bv, updwhat, updflag);
1432         /// If the action has deleted all text in the inset, we need to change the
1433         // language to the language of the surronding text.
1434         if (!was_empty && paragraphs.begin()->empty() &&
1435             boost::next(paragraphs.begin()) == paragraphs.end()) {
1436                 LyXFont font(LyXFont::ALL_IGNORE);
1437                 font.setLanguage(bv->getParentLanguage(this));
1438                 setFont(bv, font, false);
1439         }
1440
1441         if (result >= FINISHED)
1442                 bv->unlockInset(this);
1443
1444         if (result == DISPATCHED_NOUPDATE && (need_update & FULL))
1445                 result = DISPATCHED;
1446         return result;
1447 }
1448
1449
1450 int InsetText::latex(Buffer const * buf, ostream & os, bool fragile, bool) const
1451 {
1452         TexRow texrow;
1453         latexParagraphs(buf, paragraphs, os, texrow, fragile);
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(), boost::next(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         paragraphs.clear();
1949         ParagraphList::iterator pit = plist.begin();
1950         ParagraphList::iterator pend = plist.end();
1951         for (; pit != pend; ++pit) {
1952                 Paragraph * new_par = new Paragraph(*pit, same_id);
1953                 new_par->setInsetOwner(this);
1954                 paragraphs.push_back(new_par);
1955         }
1956
1957         reinitLyXText();
1958         need_update = INIT;
1959 }
1960
1961
1962 void InsetText::markNew(bool track_changes)
1963 {
1964         ParagraphList::iterator pit = paragraphs.begin();
1965         ParagraphList::iterator pend = paragraphs.end();
1966         for (; pit != pend; ++pit) {
1967                 if (track_changes) {
1968                         pit->trackChanges();
1969                 } else {
1970                         // no-op when not tracking
1971                         pit->cleanChanges();
1972                 }
1973         }
1974 }
1975
1976
1977 void InsetText::setText(string const & data, LyXFont const & font)
1978 {
1979         clear(false);
1980         for (unsigned int i = 0; i < data.length(); ++i)
1981                 paragraphs.begin()->insertChar(i, data[i], font);
1982         reinitLyXText();
1983 }
1984
1985
1986 void InsetText::setAutoBreakRows(bool flag)
1987 {
1988         if (flag != autoBreakRows) {
1989                 autoBreakRows = flag;
1990                 if (!flag)
1991                         removeNewlines();
1992                 need_update = INIT;
1993         }
1994 }
1995
1996
1997 void InsetText::setDrawFrame(BufferView * bv, DrawFrame how)
1998 {
1999         if (how != drawFrame_) {
2000                 drawFrame_ = how;
2001                 if (bv)
2002                         updateLocal(bv, DRAW_FRAME, false);
2003         }
2004 }
2005
2006
2007 void InsetText::setFrameColor(BufferView * bv, LColor::color col)
2008 {
2009         if (frame_color != col) {
2010                 frame_color = col;
2011                 if (bv)
2012                         updateLocal(bv, DRAW_FRAME, false);
2013         }
2014 }
2015
2016
2017 int InsetText::cx(BufferView * bv) const
2018 {
2019         // we do nothing dangerous so we use a local cache
2020         LyXText * llt = getLyXText(bv);
2021         int x = llt->cursor.x() + top_x + TEXT_TO_INSET_OFFSET;
2022         if (the_locking_inset) {
2023                 LyXFont font = llt->getFont(bv->buffer(), llt->cursor.par(),
2024                                             llt->cursor.pos());
2025                 if (font.isVisibleRightToLeft())
2026                         x -= the_locking_inset->width(bv, font);
2027         }
2028         return x;
2029 }
2030
2031
2032 int InsetText::cix(BufferView * bv) const
2033 {
2034         // we do nothing dangerous so we use a local cache
2035         LyXText * llt = getLyXText(bv);
2036         int x = llt->cursor.ix() + top_x + TEXT_TO_INSET_OFFSET;
2037         if (the_locking_inset) {
2038                 LyXFont font = llt->getFont(bv->buffer(), llt->cursor.par(),
2039                                             llt->cursor.pos());
2040                 if (font.isVisibleRightToLeft())
2041                         x -= the_locking_inset->width(bv, font);
2042         }
2043         return x;
2044 }
2045
2046
2047 int InsetText::cy(BufferView * bv) const
2048 {
2049         LyXFont font;
2050         return getLyXText(bv)->cursor.y() - ascent(bv, font) + TEXT_TO_INSET_OFFSET;
2051 }
2052
2053
2054 int InsetText::ciy(BufferView * bv) const
2055 {
2056         LyXFont font;
2057         return getLyXText(bv)->cursor.iy() - ascent(bv, font) + TEXT_TO_INSET_OFFSET;
2058 }
2059
2060
2061 pos_type InsetText::cpos(BufferView * bv) const
2062 {
2063         return getLyXText(bv)->cursor.pos();
2064 }
2065
2066
2067 ParagraphList::iterator InsetText::cpar(BufferView * bv) const
2068 {
2069         return getLyXText(bv)->cursor.par();
2070 }
2071
2072
2073 bool InsetText::cboundary(BufferView * bv) const
2074 {
2075         return getLyXText(bv)->cursor.boundary();
2076 }
2077
2078
2079 RowList::iterator InsetText::crow(BufferView * bv) const
2080 {
2081         return getLyXText(bv)->cursor.row();
2082 }
2083
2084
2085 LyXText * InsetText::getLyXText(BufferView const * lbv,
2086                                 bool const recursive) const
2087 {
2088         if (cached_bview == lbv) {
2089                 if (recursive && the_locking_inset)
2090                         return the_locking_inset->getLyXText(lbv, true);
2091                 LyXText * lt = cached_text.get();
2092                 lyx::Assert(lt && lt->rows().begin()->par() == paragraphs.begin());
2093                 return lt;
2094         }
2095         // Super UGLY! (Lgb)
2096         BufferView * bv = const_cast<BufferView *>(lbv);
2097
2098         cached_bview = bv;
2099         Cache::iterator it = cache.find(bv);
2100
2101         if (it != cache.end()) {
2102                 if (do_reinit) {
2103                         reinitLyXText();
2104                 } else if (do_resize) {
2105                         resizeLyXText(do_resize);
2106                 } else {
2107                         if (lt || !it->second.remove) {
2108                                 lyx::Assert(it->second.text.get());
2109                                 cached_text = it->second.text;
2110                                 if (recursive && the_locking_inset) {
2111                                         return the_locking_inset->getLyXText(bv, true);
2112                                 }
2113                                 return cached_text.get();
2114                         } else if (it->second.remove) {
2115                                 if (locked) {
2116                                         saveLyXTextState(it->second.text.get());
2117                                 } else {
2118                                         sstate.lpar = 0;
2119                                 }
2120                         }
2121                         //
2122                         // when we have to reinit the existing LyXText!
2123                         //
2124                         it->second.text->init(bv);
2125                         restoreLyXTextState(it->second.text.get());
2126                         it->second.remove = false;
2127                 }
2128                 cached_text = it->second.text;
2129                 if (the_locking_inset && recursive) {
2130                         return the_locking_inset->getLyXText(bv);
2131                 }
2132                 return cached_text.get();
2133         }
2134         ///
2135         // we are here only if we don't have a BufferView * in the cache!!!
2136         ///
2137         cached_text.reset(new LyXText(bv, const_cast<InsetText *>(this)));
2138         cached_text->init(bv);
2139         restoreLyXTextState(cached_text.get());
2140
2141         cache.insert(make_pair(bv, cached_text));
2142
2143         if (the_locking_inset && recursive) {
2144                 return the_locking_inset->getLyXText(bv);
2145         }
2146         return cached_text.get();
2147 }
2148
2149
2150 void InsetText::deleteLyXText(BufferView * bv, bool recursive) const
2151 {
2152         cached_bview = 0;
2153
2154         Cache::iterator it = cache.find(bv);
2155
2156         if (it == cache.end()) {
2157                 return;
2158         }
2159
2160         lyx::Assert(it->second.text.get());
2161
2162         it->second.remove = true;
2163         if (recursive) {
2164                 /// then remove all LyXText in text-insets
2165                 for_each(paragraphs.begin(), paragraphs.end(),
2166                          boost::bind(&Paragraph::deleteInsetsLyXText, _1, bv));
2167         }
2168 }
2169
2170
2171 void InsetText::resizeLyXText(BufferView * bv, bool force) const
2172 {
2173         if (lt) {
2174                 // we cannot resize this because we are in use!
2175                 // so do this on the next possible getLyXText()
2176                 do_resize = bv;
2177                 return;
2178         }
2179         do_resize = 0;
2180         if (boost::next(paragraphs.begin()) == paragraphs.end() &&
2181             paragraphs.begin()->empty()) { // no data, resize not neccessary!
2182                 // we have to do this as a fixed width may have changed!
2183                 LyXText * t = getLyXText(bv);
2184                 saveLyXTextState(t);
2185                 t->init(bv, true);
2186                 restoreLyXTextState(t);
2187                 return;
2188         }
2189         // one endless line, resize normally not necessary
2190         if (!force && getMaxWidth(bv, this) < 0)
2191                 return;
2192
2193         Cache::iterator it = cache.find(bv);
2194         if (it == cache.end()) {
2195                 return;
2196         }
2197         lyx::Assert(it->second.text.get());
2198
2199         LyXText * t = it->second.text.get();
2200         saveLyXTextState(t);
2201
2202         for_each(paragraphs.begin(), paragraphs.end(),
2203                  boost::bind(&Paragraph::resizeInsetsLyXText, _1, bv));
2204
2205         t->init(bv, true);
2206         restoreLyXTextState(t);
2207         if (the_locking_inset) {
2208                 inset_x = cix(bv) - top_x + drawTextXOffset;
2209                 inset_y = ciy(bv) + drawTextYOffset;
2210         }
2211
2212         t->top_y(bv->screen().topCursorVisible(t->cursor, t->top_y()));
2213         if (!owner()) {
2214                 const_cast<InsetText*>(this)->updateLocal(bv, FULL, false);
2215                 // this will scroll the screen such that the cursor becomes visible
2216                 bv->updateScrollbar();
2217         } else {
2218                 need_update |= FULL;
2219         }
2220 }
2221
2222
2223 void InsetText::reinitLyXText() const
2224 {
2225         if (lt) {
2226                 // we cannot resize this because we are in use!
2227                 // so do this on the next possible getLyXText()
2228                 do_reinit = true;
2229                 return;
2230         }
2231         do_reinit = false;
2232         do_resize = 0;
2233         for (Cache::iterator it = cache.begin(); it != cache.end(); ++it) {
2234                 lyx::Assert(it->second.text.get());
2235
2236                 LyXText * t = it->second.text.get();
2237                 BufferView * bv = it->first;
2238
2239                 saveLyXTextState(t);
2240
2241                 for_each(paragraphs.begin(), paragraphs.end(),
2242                          boost::bind(&Paragraph::resizeInsetsLyXText, _1, bv));
2243
2244                 t->init(bv, true);
2245                 restoreLyXTextState(t);
2246                 if (the_locking_inset) {
2247                         inset_x = cix(bv) - top_x + drawTextXOffset;
2248                         inset_y = ciy(bv) + drawTextYOffset;
2249                 }
2250                 t->top_y(bv->screen().topCursorVisible(t->cursor, t->top_y()));
2251                 if (!owner()) {
2252                         const_cast<InsetText*>(this)->updateLocal(bv, FULL, false);
2253                         // this will scroll the screen such that the cursor becomes visible
2254                         bv->updateScrollbar();
2255                 } else {
2256                         need_update = FULL;
2257                 }
2258         }
2259 }
2260
2261
2262 void InsetText::removeNewlines()
2263 {
2264         bool changed = false;
2265
2266         ParagraphList::iterator it = paragraphs.begin();
2267         ParagraphList::iterator end = paragraphs.end();
2268         for (; it != end; ++it) {
2269                 for (int i = 0; i < it->size(); ++i) {
2270                         if (it->isNewline(i)) {
2271                                 changed = true;
2272                                 it->erase(i);
2273                         }
2274                 }
2275         }
2276         if (changed)
2277                 reinitLyXText();
2278 }
2279
2280
2281 bool InsetText::nodraw() const
2282 {
2283         if (the_locking_inset)
2284                 return the_locking_inset->nodraw();
2285         return UpdatableInset::nodraw();
2286 }
2287
2288
2289 int InsetText::scroll(bool recursive) const
2290 {
2291         int sx = UpdatableInset::scroll(false);
2292
2293         if (recursive && the_locking_inset)
2294                 sx += the_locking_inset->scroll(recursive);
2295
2296         return sx;
2297 }
2298
2299
2300 void InsetText::selectAll(BufferView * bv)
2301 {
2302         getLyXText(bv)->cursorTop();
2303         getLyXText(bv)->selection.cursor = getLyXText(bv)->cursor;
2304         getLyXText(bv)->cursorBottom();
2305         getLyXText(bv)->setSelection();
2306 }
2307
2308
2309 void InsetText::clearSelection(BufferView * bv)
2310 {
2311         getLyXText(bv)->clearSelection();
2312 }
2313
2314
2315 void InsetText::clearInset(BufferView * bv, int start_x, int baseline) const
2316 {
2317         Painter & pain = bv->painter();
2318         int w = dim_.w;
2319         int h = dim_.a + dim_.d;
2320         int ty = baseline - dim_.a;
2321
2322         if (ty < 0) {
2323                 h += ty;
2324                 ty = 0;
2325         }
2326         if ((ty + h) > pain.paperHeight())
2327                 h = pain.paperHeight();
2328         if ((top_x + drawTextXOffset + w) > pain.paperWidth())
2329                 w = pain.paperWidth();
2330         pain.fillRectangle(start_x + 1, ty + 1, w - 3, h - 1, backgroundColor());
2331         need_update = FULL;
2332 }
2333
2334
2335 ParagraphList * InsetText::getParagraphs(int i) const
2336 {
2337         return (i == 0) ? const_cast<ParagraphList*>(&paragraphs) : 0;
2338 }
2339
2340
2341 LyXCursor const & InsetText::cursor(BufferView * bv) const
2342 {
2343         if (the_locking_inset)
2344                 return the_locking_inset->cursor(bv);
2345         return getLyXText(bv)->cursor;
2346 }
2347
2348
2349 Inset * InsetText::getInsetFromID(int id_arg) const
2350 {
2351         if (id_arg == id())
2352                 return const_cast<InsetText *>(this);
2353
2354         ParagraphList::iterator pit = paragraphs.begin();
2355         ParagraphList::iterator pend = paragraphs.end();
2356         for (; pit != pend; ++pit) {
2357                 InsetList::iterator it = pit->insetlist.begin();
2358                 InsetList::iterator end = pit->insetlist.end();
2359                 for (; it != end; ++it) {
2360                         if (it.getInset()->id() == id_arg)
2361                                 return it.getInset();
2362                         Inset * in = it.getInset()->getInsetFromID(id_arg);
2363                         if (in)
2364                                 return in;
2365                 }
2366         }
2367         return 0;
2368 }
2369
2370
2371 WordLangTuple const
2372 InsetText::selectNextWordToSpellcheck(BufferView * bv,
2373                                       float & value) const
2374 {
2375         bool clear = false;
2376         WordLangTuple word;
2377
2378         if (!lt) {
2379                 lt = getLyXText(bv);
2380                 clear = true;
2381         }
2382         if (the_locking_inset) {
2383                 word = the_locking_inset->selectNextWordToSpellcheck(bv, value);
2384                 if (!word.word().empty()) {
2385                         value += cy(bv);
2386                         if (clear)
2387                                 lt = 0;
2388                         return word;
2389                 }
2390                 // we have to go on checking so move cursor to the next char
2391                 lt->cursor.pos(lt->cursor.pos() + 1);
2392         }
2393         word = lt->selectNextWordToSpellcheck(value);
2394         if (word.word().empty())
2395                 bv->unlockInset(const_cast<InsetText *>(this));
2396         else
2397                 value = cy(bv);
2398         if (clear)
2399                 lt = 0;
2400         return word;
2401 }
2402
2403
2404 void InsetText::selectSelectedWord(BufferView * bv)
2405 {
2406         if (the_locking_inset) {
2407                 the_locking_inset->selectSelectedWord(bv);
2408                 return;
2409         }
2410         getLyXText(bv)->selectSelectedWord();
2411         updateLocal(bv, SELECTION, false);
2412 }
2413
2414
2415 void InsetText::toggleSelection(BufferView * bv, bool kill_selection)
2416 {
2417         if (the_locking_inset) {
2418                 the_locking_inset->toggleSelection(bv, kill_selection);
2419         }
2420         bool clear = false;
2421         if (!lt) {
2422                 lt = getLyXText(bv);
2423                 clear = true;
2424         }
2425
2426         int x = top_x + TEXT_TO_INSET_OFFSET;
2427
2428         RowList::iterator rowit = lt->rows().begin();
2429         RowList::iterator end = lt->rows().end();
2430         int y_offset = top_baseline - rowit->ascent_of_text();
2431         int y = y_offset;
2432         while ((rowit != end) && ((y + rowit->height()) <= 0)) {
2433                 y += rowit->height();
2434                 ++rowit;
2435         }
2436         if (y_offset < 0)
2437                 y_offset = y;
2438
2439         if (need_update & SELECTION)
2440                 need_update = NONE;
2441         bv->screen().toggleSelection(lt, bv, kill_selection, y_offset, x);
2442         if (clear)
2443                 lt = 0;
2444 }
2445
2446
2447 bool InsetText::nextChange(BufferView * bv, lyx::pos_type & length)
2448 {
2449         bool clear = false;
2450         if (!lt) {
2451                 lt = getLyXText(bv);
2452                 clear = true;
2453         }
2454         if (the_locking_inset) {
2455                 if (the_locking_inset->nextChange(bv, length))
2456                         return true;
2457                 lt->cursorRight(true);
2458         }
2459         lyxfind::SearchResult result =
2460                 lyxfind::findNextChange(bv, lt, length);
2461
2462         if (result == lyxfind::SR_FOUND) {
2463                 LyXCursor cur = lt->cursor;
2464                 bv->unlockInset(bv->theLockingInset());
2465                 if (bv->lockInset(this))
2466                         locked = true;
2467                 lt->cursor = cur;
2468                 lt->setSelectionRange(length);
2469                 updateLocal(bv, SELECTION, false);
2470         }
2471         if (clear)
2472                 lt = 0;
2473         return result != lyxfind::SR_NOT_FOUND;
2474 }
2475
2476
2477 bool InsetText::searchForward(BufferView * bv, string const & str,
2478                               bool cs, bool mw)
2479 {
2480         bool clear = false;
2481         if (!lt) {
2482                 lt = getLyXText(bv);
2483                 clear = true;
2484         }
2485         if (the_locking_inset) {
2486                 if (the_locking_inset->searchForward(bv, str, cs, mw))
2487                         return true;
2488                 lt->cursorRight(true);
2489         }
2490         lyxfind::SearchResult result =
2491                 lyxfind::LyXFind(bv, lt, str, true, cs, mw);
2492
2493         if (result == lyxfind::SR_FOUND) {
2494                 LyXCursor cur = lt->cursor;
2495                 bv->unlockInset(bv->theLockingInset());
2496                 if (bv->lockInset(this))
2497                         locked = true;
2498                 lt->cursor = cur;
2499                 lt->setSelectionRange(str.length());
2500                 updateLocal(bv, SELECTION, false);
2501         }
2502         if (clear)
2503                 lt = 0;
2504         return (result != lyxfind::SR_NOT_FOUND);
2505 }
2506
2507 bool InsetText::searchBackward(BufferView * bv, string const & str,
2508                                bool cs, bool mw)
2509 {
2510         if (the_locking_inset) {
2511                 if (the_locking_inset->searchBackward(bv, str, cs, mw))
2512                         return true;
2513         }
2514         bool clear = false;
2515         if (!lt) {
2516                 lt = getLyXText(bv);
2517                 clear = true;
2518         }
2519         if (!locked) {
2520                 ParagraphList::iterator pit = paragraphs.begin();
2521                 ParagraphList::iterator pend = paragraphs.end();
2522
2523                 while (boost::next(pit) != pend)
2524                         ++pit;
2525
2526                 lt->setCursor(pit, pit->size());
2527         }
2528         lyxfind::SearchResult result =
2529                 lyxfind::LyXFind(bv, lt, str, false, cs, mw);
2530
2531         if (result == lyxfind::SR_FOUND) {
2532                 LyXCursor cur = lt->cursor;
2533                 bv->unlockInset(bv->theLockingInset());
2534                 if (bv->lockInset(this))
2535                         locked = true;
2536                 lt->cursor = cur;
2537                 lt->setSelectionRange(str.length());
2538                 updateLocal(bv, SELECTION, false);
2539         }
2540         if (clear)
2541                 lt = 0;
2542         return (result != lyxfind::SR_NOT_FOUND);
2543 }
2544
2545
2546 bool InsetText::checkInsertChar(LyXFont & font)
2547 {
2548         if (owner())
2549                 return owner()->checkInsertChar(font);
2550         return true;
2551 }
2552
2553
2554 void InsetText::collapseParagraphs(BufferView * bv)
2555 {
2556         LyXText * llt = getLyXText(bv);
2557
2558         while (boost::next(paragraphs.begin()) != paragraphs.end()) {
2559                 if (!paragraphs.begin()->empty() &&
2560                     !boost::next(paragraphs.begin())->empty() &&
2561                         !paragraphs.begin()->isSeparator(paragraphs.begin()->size() - 1))
2562                 {
2563                         paragraphs.begin()->insertChar(paragraphs.begin()->size(), ' ');
2564                 }
2565                 if (llt->selection.set()) {
2566                         if (llt->selection.start.par() == boost::next(paragraphs.begin())) {
2567                                 llt->selection.start.par(paragraphs.begin());
2568                                 llt->selection.start.pos(
2569                                         llt->selection.start.pos() + paragraphs.begin()->size());
2570                         }
2571                         if (llt->selection.end.par() == boost::next(paragraphs.begin())) {
2572                                 llt->selection.end.par(paragraphs.begin());
2573                                 llt->selection.end.pos(
2574                                         llt->selection.end.pos() + paragraphs.begin()->size());
2575                         }
2576                 }
2577                 mergeParagraph(bv->buffer()->params, paragraphs, paragraphs.begin());
2578         }
2579         reinitLyXText();
2580 }
2581
2582
2583 void InsetText::getDrawFont(LyXFont & font) const
2584 {
2585         if (!owner())
2586                 return;
2587         owner()->getDrawFont(font);
2588 }
2589
2590
2591 void InsetText::appendParagraphs(Buffer * buffer, ParagraphList & plist)
2592 {
2593 #warning FIXME Check if Changes stuff needs changing here. (Lgb)
2594 // And it probably does. You have to take a look at this John. (Lgb)
2595 #warning John, have a look here. (Lgb)
2596 #if 0
2597         BufferParams const & bparams = buffer->params;
2598         Paragraph * buf;
2599         Paragraph * tmpbuf = newpar;
2600         Paragraph * lastbuffer = buf = new Paragraph(*tmpbuf, false);
2601         if (bparams.tracking_changes)
2602                 buf->cleanChanges();
2603
2604         while (tmpbuf->next()) {
2605                 tmpbuf = tmpbuf->next();
2606                 lastbuffer->next(new Paragraph(*tmpbuf, false));
2607                 lastbuffer->next()->previous(lastbuffer);
2608                 lastbuffer = lastbuffer->next();
2609                 if (bparams.tracking_changes)
2610                         lastbuffer->cleanChanges();
2611         }
2612
2613         lastbuffer = &*(paragraphs.begin());
2614         while (lastbuffer->next())
2615                 lastbuffer = lastbuffer->next();
2616         if (!newpar->empty() && !lastbuffer->empty() &&
2617                 !lastbuffer->isSeparator(lastbuffer->size() - 1))
2618         {
2619                 lastbuffer->insertChar(lastbuffer->size(), ' ');
2620         }
2621
2622         // make the buf exactly the same layout than our last paragraph
2623         buf->makeSameLayout(lastbuffer);
2624
2625         // paste it!
2626         lastbuffer->next(buf);
2627         buf->previous(lastbuffer);
2628         mergeParagraph(buffer->params, paragraphs, lastbuffer);
2629 #else
2630         ParagraphList::iterator pit = plist.begin();
2631         ParagraphList::iterator ins = paragraphs.insert(paragraphs.end(),
2632                                                         new Paragraph(*pit, false));
2633         ++pit;
2634         mergeParagraph(buffer->params, paragraphs, boost::prior(ins));
2635
2636         ParagraphList::iterator pend = plist.end();
2637         for (; pit != pend; ++pit) {
2638                 paragraphs.push_back(new Paragraph(*pit, false));
2639         }
2640
2641 #endif
2642
2643         reinitLyXText();
2644 }
2645
2646
2647 void InsetText::addPreview(grfx::PreviewLoader & loader) const
2648 {
2649         ParagraphList::iterator pit = paragraphs.begin();
2650         ParagraphList::iterator pend = paragraphs.end();
2651
2652         for (; pit != pend; ++pit) {
2653                 InsetList::iterator it  = pit->insetlist.begin();
2654                 InsetList::iterator end = pit->insetlist.end();
2655                 for (; it != end; ++it) {
2656                         it.getInset()->addPreview(loader);
2657                 }
2658         }
2659 }