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