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