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