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