]> git.lyx.org Git - lyx.git/blob - src/insets/insettext.C
simpler InsetText:: local updating
[lyx.git] / src / insets / insettext.C
1 /**
2  * \file insettext.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Jürgen Vigna
7  *
8  * Full author contact details are available in file CREDITS
9  */
10
11 #include <config.h>
12
13 #include "insettext.h"
14
15 #include "buffer.h"
16 #include "BufferView.h"
17 #include "bufferview_funcs.h"
18 #include "CutAndPaste.h"
19 #include "debug.h"
20 #include "dimension.h"
21 #include "funcrequest.h"
22 #include "gettext.h"
23 #include "errorlist.h"
24 #include "intl.h"
25 #include "LaTeXFeatures.h"
26 #include "LColor.h"
27 #include "Lsstream.h"
28 #include "lyxfont.h"
29 #include "lyxcursor.h"
30 #include "lyxfind.h"
31 #include "lyxlex.h"
32 #include "lyxrow.h"
33 #include "lyxrc.h"
34 #include "lyxtext.h"
35 #include "paragraph.h"
36 #include "ParagraphParameters.h"
37 #include "trans_mgr.h"
38 #include "undo_funcs.h"
39 #include "WordLangTuple.h"
40 #include "paragraph_funcs.h"
41 #include "sgml.h"
42 #include "rowpainter.h"
43 #include "insetnewline.h"
44 #include "metricsinfo.h"
45
46 #include "frontends/Alert.h"
47 #include "frontends/Dialogs.h"
48 #include "frontends/font_metrics.h"
49 #include "frontends/LyXView.h"
50 #include "frontends/Painter.h"
51 #include "frontends/screen.h"
52
53 #include "support/textutils.h"
54 #include "support/LAssert.h"
55 #include "support/lstrings.h"
56 #include "support/lyxalgo.h" // lyx::count
57
58 #include <boost/bind.hpp>
59
60 #include <fstream>
61 #include <algorithm>
62 #include <cstdlib>
63
64 using std::ostream;
65 using std::ifstream;
66 using std::endl;
67 using std::min;
68 using std::max;
69 using std::make_pair;
70 using std::vector;
71 using std::pair;
72 using std::for_each;
73 using std::auto_ptr;
74
75 using namespace lyx::support;
76 using namespace lyx::graphics;
77 using namespace bv_funcs;
78
79 using lyx::pos_type;
80 using lyx::textclass_type;
81
82
83 // we should get rid of these (Andre')
84
85 void InsetText::saveLyXTextState() const
86 {
87         // check if my paragraphs are still valid
88         ParagraphList::iterator it = const_cast<ParagraphList&>(paragraphs).begin();
89         ParagraphList::iterator end = const_cast<ParagraphList&>(paragraphs).end();
90         for (; it != end; ++it)
91                 if (it == text_.cursor.par())
92                         break;
93
94         if (it != end && text_.cursor.pos() <= it->size())
95                 sstate = text_; // slicing intended
96         else
97                 sstate.cursor.par(end);
98 }
99
100
101 void InsetText::restoreLyXTextState() const
102 {
103         if (sstate.cursor.par() == const_cast<ParagraphList&>(paragraphs).end())
104                 return;
105
106         text_.selection.set(true);
107         // at this point just to avoid the DEPM when setting the cursor
108         text_.selection.mark(sstate.selection.mark());
109         if (sstate.selection.set()) {
110                 text_.setCursor(sstate.selection.start.par(),
111                         sstate.selection.start.pos(),
112                         true, sstate.selection.start.boundary());
113                 text_.selection.cursor = text_.cursor;
114                 text_.setCursor(sstate.selection.end.par(), sstate.selection.end.pos(),
115                         true, sstate.selection.end.boundary());
116                 text_.setSelection();
117                 text_.setCursor(sstate.cursor.par(), sstate.cursor.pos());
118         } else {
119                 text_.setCursor(sstate.cursor.par(), sstate.cursor.pos(),
120                         true, sstate.cursor.boundary());
121                 text_.selection.cursor = text_.cursor;
122                 text_.selection.set(false);
123         }
124 }
125
126
127 InsetText::InsetText(BufferParams const & bp)
128         : UpdatableInset(), text_(0, this)
129 {
130         paragraphs.push_back(Paragraph());
131         paragraphs.begin()->layout(bp.getLyXTextClass().defaultLayout());
132         if (bp.tracking_changes)
133                 paragraphs.begin()->trackChanges();
134         init(0);
135 }
136
137
138 InsetText::InsetText(InsetText const & in)
139         : UpdatableInset(in), text_(0, this)
140 {
141         init(&in);
142 }
143
144
145 InsetText & InsetText::operator=(InsetText const & it)
146 {
147         init(&it);
148         return *this;
149 }
150
151
152 void InsetText::init(InsetText const * ins)
153 {
154         if (ins) {
155                 textwidth_ = ins->textwidth_;
156                 text_.bv_owner = ins->text_.bv_owner;
157                 setParagraphData(ins->paragraphs);
158                 autoBreakRows = ins->autoBreakRows;
159                 drawFrame_ = ins->drawFrame_;
160                 frame_color = ins->frame_color;
161         } else {
162                 textwidth_ = 0; // broken
163                 drawFrame_ = NEVER;
164                 frame_color = LColor::insetframe;
165                 autoBreakRows = false;
166         }
167         the_locking_inset = 0;
168         for_each(paragraphs.begin(), paragraphs.end(),
169                  boost::bind(&Paragraph::setInsetOwner, _1, this));
170         top_y = 0;
171         no_selection = true;
172         drawTextXOffset = 0;
173         drawTextYOffset = 0;
174         locked = false;
175         old_par = paragraphs.end();
176         last_drawn_width = -1;
177         sstate.cursor.par(paragraphs.end());
178         in_insetAllowed = false;
179 }
180
181
182 void InsetText::clear(bool just_mark_erased)
183 {
184         if (just_mark_erased) {
185                 ParagraphList::iterator it = paragraphs.begin();
186                 ParagraphList::iterator end = paragraphs.end();
187                 for (; it != end; ++it) {
188                         it->markErased();
189                 }
190                 return;
191         }
192
193         // This is a gross hack...
194         LyXLayout_ptr old_layout = paragraphs.begin()->layout();
195
196         paragraphs.clear();
197         paragraphs.push_back(Paragraph());
198         paragraphs.begin()->setInsetOwner(this);
199         paragraphs.begin()->layout(old_layout);
200
201         reinitLyXText();
202 }
203
204
205 auto_ptr<InsetBase> InsetText::clone() const
206 {
207         return auto_ptr<InsetBase>(new InsetText(*this));
208 }
209
210
211 void InsetText::write(Buffer const * buf, ostream & os) const
212 {
213         os << "Text\n";
214         writeParagraphData(buf, os);
215 }
216
217
218 void InsetText::writeParagraphData(Buffer const * buf, ostream & os) const
219 {
220         ParagraphList::const_iterator it = paragraphs.begin();
221         ParagraphList::const_iterator end = paragraphs.end();
222         Paragraph::depth_type dth = 0;
223         for (; it != end; ++it) {
224                 it->write(buf, os, buf->params, dth);
225         }
226 }
227
228
229 void InsetText::read(Buffer const * buf, LyXLex & lex)
230 {
231         string token;
232         Paragraph::depth_type depth = 0;
233
234         clear(false);
235
236         if (buf->params.tracking_changes)
237                 paragraphs.begin()->trackChanges();
238
239         // delete the initial paragraph
240         paragraphs.clear();
241         ParagraphList::iterator pit = paragraphs.begin();
242
243         while (lex.isOK()) {
244                 lex.nextToken();
245                 token = lex.getString();
246                 if (token.empty())
247                         continue;
248                 if (token == "\\end_inset") {
249                         break;
250                 }
251
252                 if (token == "\\end_document") {
253                         lex.printError("\\end_document read in inset! Error in document!");
254                         return;
255                 }
256
257                 // FIXME: ugly.
258                 const_cast<Buffer*>(buf)->readParagraph(lex, token, paragraphs, pit, depth);
259         }
260
261         pit = paragraphs.begin();
262         ParagraphList::iterator const end = paragraphs.end();
263         for (; pit != end; ++pit)
264                 pit->setInsetOwner(this);
265
266         if (token != "\\end_inset") {
267                 lex.printError("Missing \\end_inset at this point. "
268                                            "Read: `$$Token'");
269         }
270 }
271
272
273 void InsetText::metrics(MetricsInfo & mi, Dimension & dim) const
274 {
275         //lyxerr << "InsetText::metrics: width: " << mi.base.textwidth << endl;
276
277         textwidth_ = mi.base.textwidth;
278         BufferView * bv = mi.base.bv;
279         setViewCache(bv);
280         text_.metrics(mi, dim);
281         dim.asc += TEXT_TO_INSET_OFFSET;
282         dim.des += TEXT_TO_INSET_OFFSET;
283         dim.wid += 2 * TEXT_TO_INSET_OFFSET;
284         dim.wid = max(dim.wid, 10);
285         dim_ = dim;
286 }
287
288
289 int InsetText::textWidth() const
290 {
291         return textwidth_;
292 }
293
294
295 void InsetText::draw(PainterInfo & pi, int x, int baseline) const
296 {
297         // update our idea of where we are. Clearly, we should
298         // not have to know this information.
299         top_x = x;
300
301         int const start_x = x;
302
303         BufferView * bv = pi.base.bv;
304         Painter & pain = pi.pain;
305
306         // repaint the background if needed
307         if (backgroundColor() != LColor::background)
308                 clearInset(bv, start_x + TEXT_TO_INSET_OFFSET, baseline);
309
310         // no draw is necessary !!!
311         if (drawFrame_ == LOCKED && !locked && paragraphs.begin()->empty()) {
312                 top_baseline = baseline;
313                 return;
314         }
315
316         bv->hideCursor();
317
318         if (!owner())
319                 x += scroll();
320
321         top_baseline = baseline;
322         top_y = baseline - dim_.asc;
323
324         if (last_drawn_width != dim_.wid)
325                 last_drawn_width = dim_.wid;
326
327         if (the_locking_inset && cpar() == inset_par && cpos() == inset_pos) {
328                 inset_x = cix() - x + drawTextXOffset;
329                 inset_y = ciy() + drawTextYOffset;
330         }
331
332         x += TEXT_TO_INSET_OFFSET;
333
334         RowList::iterator rit = text_.rows().begin();
335         RowList::iterator end = text_.rows().end();
336
337         int y_offset = baseline - rit->ascent_of_text();
338         int y2 = pain.paperHeight();
339         int first = 0;
340         int y = y_offset;
341         while (rit != end && y + rit->height() <= 0) {
342                 y += rit->height();
343                 first += rit->height();
344                 ++rit;
345         }
346         if (y_offset < 0) {
347                 text_.top_y(-y_offset);
348                 first = y;
349                 y_offset = 0;
350         } else {
351                 text_.top_y(first);
352                 first = 0;
353         }
354
355         int yo = y_offset + first;
356
357         paintRows(*bv, text_, rit, x, 0, yo, y2, yo);
358
359         if (drawFrame_ == ALWAYS || (drawFrame_ == LOCKED && locked))
360                 drawFrame(pain, int(start_x));
361 }
362
363
364 void InsetText::drawFrame(Painter & pain, int x) const
365 {
366         static int const ttoD2 = TEXT_TO_INSET_OFFSET / 2;
367         frame_x = x + ttoD2;
368         frame_y = top_baseline - dim_.asc + ttoD2;
369         frame_w = dim_.wid - TEXT_TO_INSET_OFFSET;
370         frame_h = dim_.asc + dim_.des - TEXT_TO_INSET_OFFSET;
371         pain.rectangle(frame_x, frame_y, frame_w, frame_h,
372                        frame_color);
373 }
374
375
376 void InsetText::updateLocal(BufferView * bv, bool mark_dirty)
377 {
378         if (!bv)
379                 return;
380
381         if (!autoBreakRows && paragraphs.size() > 1)
382                 collapseParagraphs(bv);
383
384         text_.partialRebreak();
385         bool flag = mark_dirty || text_.selection.set();
386         if (!text_.selection.set())
387                 text_.selection.cursor = text_.cursor;
388
389         bv->fitCursor();
390
391         if (flag)
392                 bv->updateInset(const_cast<InsetText *>(this));
393
394         bv->owner()->view_state_changed();
395         bv->owner()->updateMenubar();
396         bv->owner()->updateToolbar();
397         if (old_par != cpar()) {
398                 bv->owner()->setLayout(cpar()->layout()->name());
399                 old_par = cpar();
400         }
401 }
402
403
404 string const InsetText::editMessage() const
405 {
406         return _("Opened Text Inset");
407 }
408
409
410 void InsetText::insetUnlock(BufferView * bv)
411 {
412         if (the_locking_inset) {
413                 the_locking_inset->insetUnlock(bv);
414                 the_locking_inset = 0;
415                 updateLocal(bv, false);
416         }
417         no_selection = true;
418         locked = false;
419
420         if (text_.selection.set()) {
421                 text_.clearSelection();
422         } else if (owner()) {
423                 bv->owner()->setLayout(owner()->getLyXText(bv)
424                                        ->cursor.par()->layout()->name());
425         } else
426                 bv->owner()->setLayout(bv->text->cursor.par()->layout()->name());
427         // hack for deleteEmptyParMech
428         ParagraphList::iterator first_par = paragraphs.begin();
429         if (!first_par->empty()) {
430                 text_.setCursor(first_par, 0);
431         } else if (paragraphs.size() > 1) {
432                 text_.setCursor(boost::next(first_par), 0);
433         }
434 }
435
436
437 void InsetText::lockInset(BufferView * bv)
438 {
439         locked = true;
440         the_locking_inset = 0;
441         inset_pos = inset_x = inset_y = 0;
442         inset_boundary = false;
443         inset_par = paragraphs.end();
444         old_par = paragraphs.end();
445         text_.setCursorIntern(paragraphs.begin(), 0);
446         text_.clearSelection();
447         finishUndo();
448         // If the inset is empty set the language of the current font to the
449         // language to the surronding text (if different).
450         if (paragraphs.begin()->empty() && paragraphs.size() == 1 &&
451                 bv->getParentLanguage(this) != text_.current_font.language()) {
452                 LyXFont font(LyXFont::ALL_IGNORE);
453                 font.setLanguage(bv->getParentLanguage(this));
454                 setFont(bv, font, false);
455         }
456 }
457
458
459 void InsetText::lockInset(BufferView * /*bv*/, UpdatableInset * inset)
460 {
461         the_locking_inset = inset;
462         inset_x = cix() - top_x + drawTextXOffset;
463         inset_y = ciy() + drawTextYOffset;
464         inset_pos = cpos();
465         inset_par = cpar();
466         inset_boundary = cboundary();
467 }
468
469
470 bool InsetText::lockInsetInInset(BufferView * bv, UpdatableInset * inset)
471 {
472         lyxerr[Debug::INSETS] << "InsetText::LockInsetInInset("
473                               << inset << "): " << endl;
474         if (!inset)
475                 return false;
476         if (!the_locking_inset) {
477                 ParagraphList::iterator pit = paragraphs.begin();
478                 ParagraphList::iterator pend = paragraphs.end();
479
480                 int const id = inset->id();
481                 for (; pit != pend; ++pit) {
482                         InsetList::iterator it = pit->insetlist.begin();
483                         InsetList::iterator const end = pit->insetlist.end();
484                         for (; it != end; ++it) {
485                                 if (it->inset == inset) {
486                                         lyxerr << "InsetText::lockInsetInInset: 1 a" << endl;
487                                         text_.setCursorIntern(pit, it->pos);
488                                         lyxerr << "InsetText::lockInsetInInset: 1 b" << endl;
489                                         lyxerr << "bv: " << bv << " inset: " << inset << endl;
490                                         lockInset(bv, inset);
491                                         lyxerr << "InsetText::lockInsetInInset: 1 c" << endl;
492                                         return true;
493                                 }
494                                 if (it->inset->getInsetFromID(id)) {
495                                         lyxerr << "InsetText::lockInsetInInset: 2" << endl;
496                                         text_.setCursorIntern(pit, it->pos);
497                                         it->inset->localDispatch(FuncRequest(bv, LFUN_INSET_EDIT));
498                                         return the_locking_inset->lockInsetInInset(bv, inset);
499                                 }
500                         }
501                 }
502                 lyxerr << "InsetText::lockInsetInInset: 3" << endl;
503                 return false;
504         }
505         if (inset == cpar()->getInset(cpos())) {
506                 lyxerr[Debug::INSETS] << "OK" << endl;
507                 lockInset(bv, inset);
508                 return true;
509         }
510
511         if (the_locking_inset && the_locking_inset == inset) {
512                 if (cpar() == inset_par && cpos() == inset_pos) {
513                         lyxerr[Debug::INSETS] << "OK" << endl;
514                         inset_x = cix() - top_x + drawTextXOffset;
515                         inset_y = ciy() + drawTextYOffset;
516                 } else {
517                         lyxerr[Debug::INSETS] << "cursor.pos != inset_pos" << endl;
518                 }
519         } else if (the_locking_inset) {
520                 lyxerr[Debug::INSETS] << "MAYBE" << endl;
521                 return the_locking_inset->lockInsetInInset(bv, inset);
522         }
523         lyxerr[Debug::INSETS] << "NOT OK" << endl;
524         return false;
525 }
526
527
528 bool InsetText::unlockInsetInInset(BufferView * bv, UpdatableInset * inset,
529                                    bool lr)
530 {
531         if (!the_locking_inset)
532                 return false;
533         if (the_locking_inset == inset) {
534                 the_locking_inset->insetUnlock(bv);
535                 getLyXText(bv)->updateInset(inset);
536                 the_locking_inset = 0;
537                 if (lr)
538                         moveRightIntern(bv, true, false);
539                 old_par = paragraphs.end(); // force layout setting
540                 if (scroll())
541                         scroll(bv, 0.0F);
542                 else
543                         updateLocal(bv, false);
544                 return true;
545         }
546         return the_locking_inset->unlockInsetInInset(bv, inset, lr);
547 }
548
549
550 bool InsetText::updateInsetInInset(BufferView * bv, InsetOld * inset)
551 {
552         if (!autoBreakRows && paragraphs.size() > 1)
553                 collapseParagraphs(bv);
554
555         if (inset == this)
556                 return true;
557
558         if (inset->owner() != this) {
559                 bool found = false;
560                 UpdatableInset * tl_inset = the_locking_inset;
561                 if (tl_inset)
562                         found = tl_inset->updateInsetInInset(bv, inset);
563                 if (!found) {
564                         tl_inset = static_cast<UpdatableInset *>(inset);
565                         while(tl_inset->owner() && tl_inset->owner() != this)
566                                 tl_inset = static_cast<UpdatableInset *>(tl_inset->owner());
567                         if (!tl_inset->owner())
568                                 return false;
569                         found = tl_inset->updateInsetInInset(bv, inset);
570                 } else {
571                         text_.updateInset(tl_inset);
572                 }
573                 return found;
574         }
575         bool found = text_.updateInset(inset);
576         if (found) {
577                 if (the_locking_inset &&
578                     cpar() == inset_par && cpos() == inset_pos)
579                 {
580                         inset_x = cix() - top_x + drawTextXOffset;
581                         inset_y = ciy() + drawTextYOffset;
582                 }
583         }
584         return found;
585 }
586
587
588 void InsetText::lfunMousePress(FuncRequest const & cmd)
589 {
590         no_selection = true;
591
592         // use this to check mouse motion for selection!
593         mouse_x = cmd.x;
594         mouse_y = cmd.y;
595
596         BufferView * bv = cmd.view();
597         FuncRequest cmd1 = cmd;
598         cmd1.x -= inset_x;
599         cmd1.y -= inset_y;
600         if (!locked)
601                 lockInset(bv);
602
603         int tmp_x = cmd.x - drawTextXOffset;
604         int tmp_y = cmd.y + dim_.asc - getLyXText(bv)->top_y();
605         InsetOld * inset = getLyXText(bv)->checkInsetHit(tmp_x, tmp_y);
606
607         if (the_locking_inset) {
608                 if (the_locking_inset == inset) {
609                         the_locking_inset->localDispatch(cmd1);
610                         return;
611                 }
612                 // otherwise only unlock the_locking_inset
613                 the_locking_inset->insetUnlock(bv);
614                 the_locking_inset = 0;
615         }
616         if (!inset)
617                 no_selection = false;
618
619         if (bv->theLockingInset()) {
620                 if (isHighlyEditableInset(inset)) {
621                         // We just have to lock the inset before calling a
622                         // PressEvent on it!
623                         UpdatableInset * uinset = static_cast<UpdatableInset*>(inset);
624                         if (!bv->lockInset(uinset)) {
625                                 lyxerr[Debug::INSETS] << "Cannot lock inset" << endl;
626                         }
627                         inset->localDispatch(cmd1);
628                         if (the_locking_inset)
629                                 updateLocal(bv, false);
630                         return;
631                 }
632         }
633         if (!inset) {
634                 bool paste_internally = false;
635                 if (cmd.button() == mouse_button::button2 && getLyXText(bv)->selection.set()) {
636                         localDispatch(FuncRequest(bv, LFUN_COPY));
637                         paste_internally = true;
638                 }
639                 int old_top_y = text_.top_y();
640
641                 text_.setCursorFromCoordinates(cmd.x - drawTextXOffset,
642                                              cmd.y + dim_.asc);
643                 // set the selection cursor!
644                 text_.selection.cursor = text_.cursor;
645                 text_.cursor.x_fix(text_.cursor.x());
646
647                 text_.clearSelection();
648                 updateLocal(bv, false);
649
650                 bv->owner()->setLayout(cpar()->layout()->name());
651
652                 // we moved the view we cannot do mouse selection in this case!
653                 if (getLyXText(bv)->top_y() != old_top_y)
654                         no_selection = true;
655                 old_par = cpar();
656                 // Insert primary selection with middle mouse
657                 // if there is a local selection in the current buffer,
658                 // insert this
659                 if (cmd.button() == mouse_button::button2) {
660                         if (paste_internally)
661                                 localDispatch(FuncRequest(bv, LFUN_PASTE));
662                         else
663                                 localDispatch(FuncRequest(bv, LFUN_PASTESELECTION, "paragraph"));
664                 }
665         } else {
666                 getLyXText(bv)->clearSelection();
667         }
668 }
669
670
671 bool InsetText::lfunMouseRelease(FuncRequest const & cmd)
672 {
673         BufferView * bv = cmd.view();
674         FuncRequest cmd1 = cmd;
675         cmd1.x -= inset_x;
676         cmd1.y -= inset_y;
677
678         no_selection = true;
679         if (the_locking_inset)
680                 return the_locking_inset->localDispatch(cmd1);
681
682         int tmp_x = cmd.x - drawTextXOffset;
683         int tmp_y = cmd.y + dim_.asc - getLyXText(bv)->top_y();
684         InsetOld * inset = getLyXText(bv)->checkInsetHit(tmp_x, tmp_y);
685         bool ret = false;
686         if (inset) {
687 // This code should probably be removed now. Simple insets
688 // (!highlyEditable) can actually take the localDispatch,
689 // and turn it into edit() if necessary. But we still
690 // need to deal properly with the whole relative vs.
691 // absolute mouse co-ords thing in a realiable, sensible way
692 #if 0
693                 if (isHighlyEditableInset(inset))
694                         ret = inset->localDispatch(cmd1);
695                 else {
696                         inset_x = cix(bv) - top_x + drawTextXOffset;
697                         inset_y = ciy() + drawTextYOffset;
698                         cmd1.x = cmd.x - inset_x;
699                         cmd1.y = cmd.x - inset_y;
700                         inset->edit(bv, cmd1.x, cmd1.y, cmd.button());
701                         ret = true;
702                 }
703 #endif
704                 ret = inset->localDispatch(cmd1);
705                 updateLocal(bv, false);
706
707         }
708         return ret;
709 }
710
711
712 void InsetText::lfunMouseMotion(FuncRequest const & cmd)
713 {
714         FuncRequest cmd1 = cmd;
715         cmd1.x -= inset_x;
716         cmd1.y -= inset_y;
717
718         if (the_locking_inset) {
719                 the_locking_inset->localDispatch(cmd1);
720                 return;
721         }
722
723         if (no_selection || (mouse_x == cmd.x && mouse_y == cmd.y))
724                 return;
725
726         BufferView * bv = cmd.view();
727         LyXCursor cur = text_.cursor;
728         text_.setCursorFromCoordinates
729                 (cmd.x - drawTextXOffset, cmd.y + dim_.asc);
730         text_.cursor.x_fix(text_.cursor.x());
731         if (cur == text_.cursor)
732                 return;
733         text_.setSelection();
734         updateLocal(bv, false);
735 }
736
737
738 InsetOld::RESULT InsetText::localDispatch(FuncRequest const & cmd)
739 {
740         BufferView * bv = cmd.view();
741         setViewCache(bv);
742
743         switch (cmd.action) {
744         case LFUN_INSET_EDIT: {
745                 UpdatableInset::localDispatch(cmd);
746
747                 if (!bv->lockInset(this)) {
748                         lyxerr[Debug::INSETS] << "Cannot lock inset" << endl;
749                         return DISPATCHED;
750                 }
751
752                 locked = true;
753                 the_locking_inset = 0;
754                 inset_pos = 0;
755                 inset_x = 0;
756                 inset_y = 0;
757                 inset_boundary = false;
758                 inset_par = paragraphs.end();
759                 old_par = paragraphs.end();
760
761
762                 if (cmd.argument.size()) {
763                         if (cmd.argument == "left")
764                                 text_.setCursorIntern(paragraphs.begin(), 0);
765                         else {
766                                 ParagraphList::iterator it = boost::prior(paragraphs.end());
767                                 text_.setCursor(it, it->size());
768                         }
769                 } else {
770                         int tmp_y = (cmd.y < 0) ? 0 : cmd.y;
771                         // we put here -1 and not button as now the button in the
772                         // edit call should not be needed we will fix this in 1.3.x
773                         // cycle hopefully (Jug 20020509)
774                         // FIXME: GUII I've changed this to none: probably WRONG
775                         if (!checkAndActivateInset(bv, cmd.x, tmp_y, mouse_button::none)) {
776                                 text_.setCursorFromCoordinates(cmd.x - drawTextXOffset,
777                                                                         cmd.y + dim_.asc);
778                                 text_.cursor.x_fix(text_.cursor.x());
779                         }
780                 }
781
782                 text_.clearSelection();
783                 finishUndo();
784
785                 // If the inset is empty set the language of the current font to the
786                 // language to the surronding text (if different).
787                 if (paragraphs.begin()->empty() &&
788                     paragraphs.size() == 1 &&
789                     bv->getParentLanguage(this) != text_.current_font.language())
790                 {
791                         LyXFont font(LyXFont::ALL_IGNORE);
792                         font.setLanguage(bv->getParentLanguage(this));
793                         setFont(bv, font, false);
794                 }
795
796                 updateLocal(bv, false);
797                 // Tell the paragraph dialog that we've entered an insettext.
798                 bv->dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
799                 return DISPATCHED;
800         }
801
802         case LFUN_MOUSE_PRESS:
803                 lfunMousePress(cmd);
804                 return DISPATCHED;
805
806         case LFUN_MOUSE_MOTION:
807                 lfunMouseMotion(cmd);
808                 return DISPATCHED;
809
810         case LFUN_MOUSE_RELEASE:
811                 return lfunMouseRelease(cmd) ? DISPATCHED : UNDISPATCHED;
812
813         default:
814                 break;
815         }
816
817         bool was_empty = (paragraphs.begin()->empty() &&
818                           paragraphs.size() == 1);
819
820         no_selection = false;
821         RESULT result = UpdatableInset::localDispatch(cmd);
822         if (result != UNDISPATCHED)
823                 return DISPATCHED;
824
825         result = DISPATCHED;
826         if (cmd.action < 0 && cmd.argument.empty())
827                 return FINISHED;
828
829         if (the_locking_inset) {
830                 result = the_locking_inset->localDispatch(cmd);
831                 if (result == DISPATCHED_NOUPDATE)
832                         return result;
833                 if (result == DISPATCHED) {
834                         updateLocal(bv, false);
835                         return result;
836                 }
837                 if (result >= FINISHED) {
838                         switch (result) {
839                         case FINISHED_RIGHT:
840                                 moveRightIntern(bv, false, false);
841                                 result = DISPATCHED;
842                                 break;
843                         case FINISHED_UP:
844                                 result = moveUp(bv);
845                                 if (result >= FINISHED) {
846                                         updateLocal(bv, false);
847                                         bv->unlockInset(this);
848                                 }
849                                 break;
850                         case FINISHED_DOWN:
851                                 result = moveDown(bv);
852                                 if (result >= FINISHED) {
853                                         updateLocal(bv, false);
854                                         bv->unlockInset(this);
855                                 }
856                                 break;
857                         default:
858                                 result = DISPATCHED;
859                                 break;
860                         }
861                         the_locking_inset = 0;
862                         updateLocal(bv, false);
863                         // make sure status gets reset immediately
864                         bv->owner()->clearMessage();
865                         return result;
866                 }
867         }
868         bool updflag = false;
869
870         switch (cmd.action) {
871
872         // Normal chars
873         case LFUN_SELFINSERT:
874                 if (bv->buffer()->isReadonly()) {
875 //          setErrorMessage(N_("Document is read only"));
876                         break;
877                 }
878                 if (!cmd.argument.empty()) {
879                         /* Automatically delete the currently selected
880                          * text and replace it with what is being
881                          * typed in now. Depends on lyxrc settings
882                          * "auto_region_delete", which defaults to
883                          * true (on). */
884 #if 0
885                         // This should not be needed here and is also WRONG!
886                         recordUndo(bv, Undo::INSERT, text_.cursor.par());
887 #endif
888                         bv->switchKeyMap();
889                         if (lyxrc.auto_region_delete) {
890                                 if (text_.selection.set()) {
891                                         text_.cutSelection(false, false);
892                                 }
893                         }
894                         text_.clearSelection();
895                         for (string::size_type i = 0; i < cmd.argument.length(); ++i) {
896                                 bv->owner()->getIntl().getTransManager().
897                                         TranslateAndInsert(cmd.argument[i], &text_);
898                         }
899                 }
900                 text_.selection.cursor = text_.cursor;
901                 updflag = true;
902                 result = DISPATCHED_NOUPDATE;
903                 break;
904
905         // cursor movements that need special handling
906
907         case LFUN_RIGHT:
908                 result = moveRight(bv);
909                 finishUndo();
910                 break;
911         case LFUN_LEFT:
912                 finishUndo();
913                 result = moveLeft(bv);
914                 break;
915         case LFUN_DOWN:
916                 finishUndo();
917                 result = moveDown(bv);
918                 break;
919         case LFUN_UP:
920                 finishUndo();
921                 result = moveUp(bv);
922                 break;
923
924         case LFUN_PRIOR:
925                 if (crow() == text_.rows().begin())
926                         result = FINISHED_UP;
927                 else {
928                         text_.cursorPrevious();
929                         text_.clearSelection();
930                         result = DISPATCHED_NOUPDATE;
931                 }
932                 break;
933
934         case LFUN_NEXT:
935                 if (boost::next(crow()) == text_.rows().end())
936                         result = FINISHED_DOWN;
937                 else {
938                         text_.cursorNext();
939                         text_.clearSelection();
940                         result = DISPATCHED_NOUPDATE;
941                 }
942                 break;
943
944         case LFUN_BACKSPACE: {
945                 if (text_.selection.set())
946                         text_.cutSelection(true, false);
947                 else
948                         text_.backspace();
949                 updflag = true;
950                 break;
951         }
952
953         case LFUN_DELETE: {
954                 if (text_.selection.set()) {
955                         text_.cutSelection(true, false);
956                 } else {
957                         text_.Delete();
958                 }
959                 updflag = true;
960                 break;
961         }
962
963         case LFUN_CUT: {
964                 text_.cutSelection(true, true);
965                 updflag = true;
966                 break;
967         }
968
969         case LFUN_COPY:
970                 finishUndo();
971                 text_.copySelection();
972                 break;
973
974         case LFUN_PASTESELECTION:
975         {
976                 string const clip(bv->getClipboard());
977
978                 if (clip.empty())
979                         break;
980                 if (cmd.argument == "paragraph") {
981                         text_.insertStringAsParagraphs(clip);
982                 } else {
983                         text_.insertStringAsLines(clip);
984                 }
985                 // bug 393
986                 text_.clearSelection();
987
988                 updflag = true;
989                 break;
990         }
991
992         case LFUN_PASTE: {
993                 if (!autoBreakRows) {
994                         if (CutAndPaste::nrOfParagraphs() > 1) {
995 #ifdef WITH_WARNINGS
996 #warning FIXME horrendously bad UI
997 #endif
998                                 Alert::error(_("Paste failed"), _("Cannot include more than one paragraph."));
999                                 break;
1000                         }
1001                 }
1002
1003                 replaceSelection(bv->getLyXText());
1004                 size_t sel_index = 0;
1005                 string const & arg = cmd.argument;
1006                 if (isStrUnsignedInt(arg)) {
1007                         size_t const paste_arg = strToUnsignedInt(arg);
1008 #warning FIXME Check if the arg is in the domain of available selections.
1009                         sel_index = paste_arg;
1010                 }
1011                 text_.pasteSelection(sel_index);
1012                 // bug 393
1013                 text_.clearSelection();
1014                 updflag = true;
1015                 break;
1016         }
1017
1018         case LFUN_BREAKPARAGRAPH:
1019                 if (!autoBreakRows) {
1020                         result = DISPATCHED;
1021                         break;
1022                 }
1023                 replaceSelection(bv->getLyXText());
1024                 text_.breakParagraph(paragraphs, 0);
1025                 updflag = true;
1026                 break;
1027
1028         case LFUN_BREAKPARAGRAPHKEEPLAYOUT:
1029                 if (!autoBreakRows) {
1030                         result = DISPATCHED;
1031                         break;
1032                 }
1033                 replaceSelection(bv->getLyXText());
1034                 text_.breakParagraph(paragraphs, 1);
1035                 updflag = true;
1036                 break;
1037
1038         case LFUN_BREAKLINE: {
1039                 if (!autoBreakRows) {
1040                         result = DISPATCHED;
1041                         break;
1042                 }
1043
1044                 replaceSelection(bv->getLyXText());
1045                 text_.insertInset(new InsetNewline);
1046                 updflag = true;
1047                 break;
1048         }
1049
1050         case LFUN_LAYOUT:
1051                 // do not set layouts on non breakable textinsets
1052                 if (autoBreakRows) {
1053                         string cur_layout = cpar()->layout()->name();
1054
1055                         // Derive layout number from given argument (string)
1056                         // and current buffer's textclass (number). */
1057                         LyXTextClass const & tclass =
1058                                 bv->buffer()->params.getLyXTextClass();
1059                         string layout = cmd.argument;
1060                         bool hasLayout = tclass.hasLayout(layout);
1061
1062                         // If the entry is obsolete, use the new one instead.
1063                         if (hasLayout) {
1064                                 string const & obs =
1065                                         tclass[layout]->obsoleted_by();
1066                                 if (!obs.empty())
1067                                         layout = obs;
1068                         }
1069
1070                         // see if we found the layout number:
1071                         if (!hasLayout) {
1072                                 FuncRequest lf(LFUN_MESSAGE, N_("Layout ") + cmd.argument + N_(" not known"));
1073                                 bv->owner()->dispatch(lf);
1074                                 break;
1075                         }
1076
1077                         if (cur_layout != layout) {
1078                                 cur_layout = layout;
1079                                 text_.setLayout(layout);
1080                                 bv->owner()->setLayout(cpar()->layout()->name());
1081                                 updflag = true;
1082                         }
1083                 } else {
1084                         // reset the layout box
1085                         bv->owner()->setLayout(cpar()->layout()->name());
1086                 }
1087                 break;
1088         case LFUN_PARAGRAPH_SPACING:
1089                 // This one is absolutely not working. When fiddling with this
1090                 // it also seems to me that the paragraphs inside the insettext
1091                 // inherit bufferparams/paragraphparams in a strange way. (Lgb)
1092                 // FIXME: how old is this comment ? ...
1093         {
1094                 ParagraphList::iterator pit = text_.cursor.par();
1095                 Spacing::Space cur_spacing = pit->params().spacing().getSpace();
1096                 float cur_value = 1.0;
1097                 if (cur_spacing == Spacing::Other) {
1098                         cur_value = pit->params().spacing().getValue();
1099                 }
1100
1101                 istringstream istr(STRCONV(cmd.argument));
1102                 string tmp;
1103                 istr >> tmp;
1104                 Spacing::Space new_spacing = cur_spacing;
1105                 float new_value = cur_value;
1106                 if (tmp.empty()) {
1107                         lyxerr << "Missing argument to `paragraph-spacing'"
1108                                    << endl;
1109                 } else if (tmp == "single") {
1110                         new_spacing = Spacing::Single;
1111                 } else if (tmp == "onehalf") {
1112                         new_spacing = Spacing::Onehalf;
1113                 } else if (tmp == "double") {
1114                         new_spacing = Spacing::Double;
1115                 } else if (tmp == "other") {
1116                         new_spacing = Spacing::Other;
1117                         float tmpval = 0.0;
1118                         istr >> tmpval;
1119                         lyxerr << "new_value = " << tmpval << endl;
1120                         if (tmpval != 0.0)
1121                                 new_value = tmpval;
1122                 } else if (tmp == "default") {
1123                         new_spacing = Spacing::Default;
1124                 } else {
1125                         lyxerr << _("Unknown spacing argument: ")
1126                                    << cmd.argument << endl;
1127                 }
1128                 if (cur_spacing != new_spacing || cur_value != new_value) {
1129                         pit->params().spacing(Spacing(new_spacing, new_value));
1130                         updflag = true;
1131                 }
1132         }
1133         break;
1134
1135         // These need to do repaints but don't require
1136         // special handling otherwise. A *lot* of the
1137         // above could probably be done similarly ...
1138
1139         case LFUN_HOME:
1140         case LFUN_END:
1141         case LFUN_WORDLEFT:
1142         case LFUN_WORDRIGHT:
1143         // these two are really unhandled ...
1144         case LFUN_ENDBUF:
1145         case LFUN_BEGINNINGBUF:
1146                 if (!bv->dispatch(cmd))
1147                         result = UNDISPATCHED;
1148                 break;
1149
1150         case LFUN_RIGHTSEL:
1151         case LFUN_UPSEL:
1152         case LFUN_DOWNSEL:
1153         case LFUN_LEFTSEL:
1154         case LFUN_HOMESEL:
1155         case LFUN_ENDSEL:
1156         case LFUN_WORDLEFTSEL:
1157         case LFUN_WORDRIGHTSEL:
1158
1159                 // fallthrough
1160
1161         default:
1162                 if (!bv->dispatch(cmd))
1163                         result = UNDISPATCHED;
1164                 break;
1165         }
1166
1167         updateLocal(bv, updflag);
1168
1169         /// If the action has deleted all text in the inset, we need to change the
1170         // language to the language of the surronding text.
1171         if (!was_empty && paragraphs.begin()->empty() &&
1172             paragraphs.size() == 1) {
1173                 LyXFont font(LyXFont::ALL_IGNORE);
1174                 font.setLanguage(bv->getParentLanguage(this));
1175                 setFont(bv, font, false);
1176         }
1177
1178         if (result >= FINISHED)
1179                 bv->unlockInset(this);
1180
1181         if (result == DISPATCHED_NOUPDATE)
1182                 result = DISPATCHED;
1183         return result;
1184 }
1185
1186
1187 int InsetText::latex(Buffer const * buf, ostream & os,
1188                      LatexRunParams const & runparams) const
1189 {
1190         TexRow texrow;
1191         latexParagraphs(buf, paragraphs, os, texrow, runparams);
1192         return texrow.rows();
1193 }
1194
1195
1196 int InsetText::ascii(Buffer const * buf, ostream & os, int linelen) const
1197 {
1198         unsigned int lines = 0;
1199
1200         ParagraphList::const_iterator beg = paragraphs.begin();
1201         ParagraphList::const_iterator end = paragraphs.end();
1202         ParagraphList::const_iterator it = beg;
1203         for (; it != end; ++it) {
1204                 string const tmp = buf->asciiParagraph(*it, linelen, it == beg);
1205                 lines += lyx::count(tmp.begin(), tmp.end(), '\n');
1206                 os << tmp;
1207         }
1208         return lines;
1209 }
1210
1211
1212 int InsetText::linuxdoc(Buffer const * buf, ostream & os) const
1213 {
1214         ParagraphList::iterator pit = const_cast<ParagraphList&>(paragraphs).begin();
1215         ParagraphList::iterator pend = const_cast<ParagraphList&>(paragraphs).end();
1216
1217         // There is a confusion between the empty paragraph and the default paragraph
1218         // The default paragraph is <p></p>, the empty paragraph is *empty*
1219         // Since none of the floats of linuxdoc accepts standard paragraphs
1220         // I disable them. I don't expect problems. (jamatos 2003/07/27)
1221         for (; pit != pend; ++pit) {
1222                 const string name = pit->layout()->latexname();
1223                 if (name != "p")
1224                         sgml::openTag(os, 1, 0, name);
1225                 buf->simpleLinuxDocOnePar(os, pit, 0);
1226                 if (name != "p")
1227                         sgml::closeTag(os, 1, 0, name);
1228         }
1229         return 0;
1230 }
1231
1232
1233 int InsetText::docbook(Buffer const * buf, ostream & os, bool mixcont) const
1234 {
1235         unsigned int lines = 0;
1236
1237         vector<string> environment_stack(10);
1238         vector<string> environment_inner(10);
1239
1240         int const command_depth = 0;
1241         string item_name;
1242
1243         Paragraph::depth_type depth = 0; // paragraph depth
1244
1245         ParagraphList::iterator pit = const_cast<ParagraphList&>(paragraphs).begin();
1246         ParagraphList::iterator pend = const_cast<ParagraphList&>(paragraphs).end();
1247
1248         for (; pit != pend; ++pit) {
1249                 string sgmlparam;
1250                 int desc_on = 0; // description mode
1251
1252                 LyXLayout_ptr const & style = pit->layout();
1253
1254                 // environment tag closing
1255                 for (; depth > pit->params().depth(); --depth) {
1256                         if (environment_inner[depth] != "!-- --") {
1257                                 item_name = "listitem";
1258                                 lines += sgml::closeTag(os, command_depth + depth, mixcont, item_name);
1259                                 if (environment_inner[depth] == "varlistentry")
1260                                         lines += sgml::closeTag(os, depth+command_depth, mixcont, environment_inner[depth]);
1261                         }
1262                         lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_stack[depth]);
1263                         environment_stack[depth].erase();
1264                         environment_inner[depth].erase();
1265                 }
1266
1267                 if (depth == pit->params().depth()
1268                    && environment_stack[depth] != style->latexname()
1269                    && !environment_stack[depth].empty()) {
1270                         if (environment_inner[depth] != "!-- --") {
1271                                 item_name= "listitem";
1272                                 lines += sgml::closeTag(os, command_depth+depth, mixcont, item_name);
1273                                 if (environment_inner[depth] == "varlistentry")
1274                                         lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_inner[depth]);
1275                         }
1276
1277                         lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_stack[depth]);
1278
1279                         environment_stack[depth].erase();
1280                         environment_inner[depth].erase();
1281                 }
1282
1283                 // Write opening SGML tags.
1284                 switch (style->latextype) {
1285                 case LATEX_PARAGRAPH:
1286                         lines += sgml::openTag(os, depth + command_depth, mixcont, style->latexname());
1287                         break;
1288
1289                 case LATEX_COMMAND:
1290                         buf->error(ErrorItem(_("Error"), _("LatexType Command not allowed here.\n"), pit->id(), 0, pit->size()));
1291                         return -1;
1292                         break;
1293
1294                 case LATEX_ENVIRONMENT:
1295                 case LATEX_ITEM_ENVIRONMENT:
1296                         if (depth < pit->params().depth()) {
1297                                 depth = pit->params().depth();
1298                                 environment_stack[depth].erase();
1299                         }
1300
1301                         if (environment_stack[depth] != style->latexname()) {
1302                                 if (environment_stack.size() == depth + 1) {
1303                                         environment_stack.push_back("!-- --");
1304                                         environment_inner.push_back("!-- --");
1305                                 }
1306                                 environment_stack[depth] = style->latexname();
1307                                 environment_inner[depth] = "!-- --";
1308                                 lines += sgml::openTag(os, depth + command_depth, mixcont, environment_stack[depth]);
1309                         } else {
1310                                 if (environment_inner[depth] != "!-- --") {
1311                                         item_name= "listitem";
1312                                         lines += sgml::closeTag(os, command_depth + depth, mixcont, item_name);
1313                                         if (environment_inner[depth] == "varlistentry")
1314                                                 lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_inner[depth]);
1315                                 }
1316                         }
1317
1318                         if (style->latextype == LATEX_ENVIRONMENT) {
1319                                 if (!style->latexparam().empty()) {
1320                                         if (style->latexparam() == "CDATA")
1321                                                 os << "<![CDATA[";
1322                                         else
1323                                           lines += sgml::openTag(os, depth + command_depth, mixcont, style->latexparam());
1324                                 }
1325                                 break;
1326                         }
1327
1328                         desc_on = (style->labeltype == LABEL_MANUAL);
1329
1330                         environment_inner[depth] = desc_on ? "varlistentry" : "listitem";
1331                         lines += sgml::openTag(os, depth + 1 + command_depth, mixcont, environment_inner[depth]);
1332
1333                         item_name = desc_on ? "term" : "para";
1334                         lines += sgml::openTag(os, depth + 1 + command_depth, mixcont, item_name);
1335
1336                         break;
1337                 default:
1338                         lines += sgml::openTag(os, depth + command_depth, mixcont, style->latexname());
1339                         break;
1340                 }
1341
1342                 buf->simpleDocBookOnePar(os, pit, desc_on, depth + 1 + command_depth);
1343
1344                 string end_tag;
1345                 // write closing SGML tags
1346                 switch (style->latextype) {
1347                 case LATEX_ENVIRONMENT:
1348                         if (!style->latexparam().empty()) {
1349                                 if (style->latexparam() == "CDATA")
1350                                         os << "]]>";
1351                                 else
1352                                         lines += sgml::closeTag(os, depth + command_depth, mixcont, style->latexparam());
1353                         }
1354                         break;
1355                 case LATEX_ITEM_ENVIRONMENT:
1356                         if (desc_on == 1) break;
1357                         end_tag= "para";
1358                         lines += sgml::closeTag(os, depth + 1 + command_depth, mixcont, end_tag);
1359                         break;
1360                 case LATEX_PARAGRAPH:
1361                         lines += sgml::closeTag(os, depth + command_depth, mixcont, style->latexname());
1362                         break;
1363                 default:
1364                         lines += sgml::closeTag(os, depth + command_depth, mixcont, style->latexname());
1365                         break;
1366                 }
1367         }
1368
1369         // Close open tags
1370         for (int d = depth; d >= 0; --d) {
1371                 if (!environment_stack[depth].empty()) {
1372                         if (environment_inner[depth] != "!-- --") {
1373                                 item_name = "listitem";
1374                                 lines += sgml::closeTag(os, command_depth + depth, mixcont, item_name);
1375                                if (environment_inner[depth] == "varlistentry")
1376                                        lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_inner[depth]);
1377                         }
1378
1379                         lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_stack[depth]);
1380                 }
1381         }
1382
1383         return lines;
1384 }
1385
1386
1387 void InsetText::validate(LaTeXFeatures & features) const
1388 {
1389         for_each(paragraphs.begin(), paragraphs.end(),
1390                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1391 }
1392
1393
1394 void InsetText::getCursor(BufferView & bv, int & x, int & y) const
1395 {
1396         if (the_locking_inset) {
1397                 the_locking_inset->getCursor(bv, x, y);
1398                 return;
1399         }
1400         x = cx();
1401         y = cy() + InsetText::y();
1402 }
1403
1404
1405 void InsetText::getCursorPos(BufferView * bv, int & x, int & y) const
1406 {
1407         if (the_locking_inset) {
1408                 the_locking_inset->getCursorPos(bv, x, y);
1409                 return;
1410         }
1411         x = cx() - top_x - TEXT_TO_INSET_OFFSET;
1412         y = cy() - TEXT_TO_INSET_OFFSET;
1413 }
1414
1415
1416 int InsetText::insetInInsetY() const
1417 {
1418         if (!the_locking_inset)
1419                 return 0;
1420
1421         return inset_y + the_locking_inset->insetInInsetY();
1422 }
1423
1424
1425 void InsetText::fitInsetCursor(BufferView * bv) const
1426 {
1427         if (the_locking_inset) {
1428                 the_locking_inset->fitInsetCursor(bv);
1429                 return;
1430         }
1431
1432         LyXFont const font = text_.getFont(cpar(), cpos());
1433
1434         int const asc = font_metrics::maxAscent(font);
1435         int const desc = font_metrics::maxDescent(font);
1436
1437         bv->fitLockedInsetCursor(cx(), cy(), asc, desc);
1438 }
1439
1440
1441 InsetOld::RESULT
1442 InsetText::moveRight(BufferView * bv, bool activate_inset, bool selecting)
1443 {
1444         if (text_.cursor.par()->isRightToLeftPar(bv->buffer()->params))
1445                 return moveLeftIntern(bv, false, activate_inset, selecting);
1446         else
1447                 return moveRightIntern(bv, true, activate_inset, selecting);
1448 }
1449
1450
1451 InsetOld::RESULT
1452 InsetText::moveLeft(BufferView * bv, bool activate_inset, bool selecting)
1453 {
1454         if (text_.cursor.par()->isRightToLeftPar(bv->buffer()->params))
1455                 return moveRightIntern(bv, true, activate_inset, selecting);
1456         else
1457                 return moveLeftIntern(bv, false, activate_inset, selecting);
1458 }
1459
1460
1461 InsetOld::RESULT
1462 InsetText::moveRightIntern(BufferView * bv, bool front,
1463                            bool activate_inset, bool selecting)
1464 {
1465         ParagraphList::iterator c_par = cpar();
1466
1467         if (boost::next(c_par) == paragraphs.end() && cpos() >= c_par->size())
1468                 return FINISHED_RIGHT;
1469         if (activate_inset && checkAndActivateInset(bv, front))
1470                 return DISPATCHED;
1471         text_.cursorRight(bv);
1472         if (!selecting)
1473                 text_.clearSelection();
1474         return DISPATCHED_NOUPDATE;
1475 }
1476
1477
1478 InsetOld::RESULT
1479 InsetText::moveLeftIntern(BufferView * bv, bool front,
1480                           bool activate_inset, bool selecting)
1481 {
1482         if (cpar() == paragraphs.begin() && cpos() <= 0)
1483                 return FINISHED;
1484         text_.cursorLeft(bv);
1485         if (!selecting)
1486                 text_.clearSelection();
1487         if (activate_inset && checkAndActivateInset(bv, front))
1488                 return DISPATCHED;
1489         return DISPATCHED_NOUPDATE;
1490 }
1491
1492
1493 InsetOld::RESULT InsetText::moveUp(BufferView * bv)
1494 {
1495         if (crow() == text_.rows().begin())
1496                 return FINISHED_UP;
1497         text_.cursorUp(bv);
1498         text_.clearSelection();
1499         return DISPATCHED_NOUPDATE;
1500 }
1501
1502
1503 InsetOld::RESULT InsetText::moveDown(BufferView * bv)
1504 {
1505         if (boost::next(crow()) == text_.rows().end())
1506                 return FINISHED_DOWN;
1507         text_.cursorDown(bv);
1508         text_.clearSelection();
1509         return DISPATCHED_NOUPDATE;
1510 }
1511
1512
1513 bool InsetText::insertInset(BufferView * bv, InsetOld * inset)
1514 {
1515         if (the_locking_inset) {
1516                 if (the_locking_inset->insetAllowed(inset))
1517                         return the_locking_inset->insertInset(bv, inset);
1518                 return false;
1519         }
1520         inset->setOwner(this);
1521         text_.insertInset(inset);
1522         bv->fitCursor();
1523         updateLocal(bv, true);
1524         return true;
1525 }
1526
1527
1528 bool InsetText::insetAllowed(InsetOld::Code code) const
1529 {
1530         // in_insetAllowed is a really gross hack,
1531         // to allow us to call the owner's insetAllowed
1532         // without stack overflow, which can happen
1533         // when the owner uses InsetCollapsable::insetAllowed()
1534         bool ret = true;
1535         if (in_insetAllowed)
1536                 return ret;
1537         in_insetAllowed = true;
1538         if (the_locking_inset)
1539                 ret = the_locking_inset->insetAllowed(code);
1540         else if (owner())
1541                 ret = owner()->insetAllowed(code);
1542         in_insetAllowed = false;
1543         return ret;
1544 }
1545
1546
1547 UpdatableInset * InsetText::getLockingInset() const
1548 {
1549         return the_locking_inset ? the_locking_inset->getLockingInset() :
1550                 const_cast<InsetText *>(this);
1551 }
1552
1553
1554 UpdatableInset * InsetText::getFirstLockingInsetOfType(InsetOld::Code c)
1555 {
1556         if (c == lyxCode())
1557                 return this;
1558         if (the_locking_inset)
1559                 return the_locking_inset->getFirstLockingInsetOfType(c);
1560         return 0;
1561 }
1562
1563
1564 bool InsetText::showInsetDialog(BufferView * bv) const
1565 {
1566         if (the_locking_inset)
1567                 return the_locking_inset->showInsetDialog(bv);
1568         return false;
1569 }
1570
1571
1572 void InsetText::getLabelList(std::vector<string> & list) const
1573 {
1574         ParagraphList::const_iterator pit = paragraphs.begin();
1575         ParagraphList::const_iterator pend = paragraphs.end();
1576         for (; pit != pend; ++pit) {
1577                 InsetList::const_iterator beg = pit->insetlist.begin();
1578                 InsetList::const_iterator end = pit->insetlist.end();
1579                 for (; beg != end; ++beg)
1580                         beg->inset->getLabelList(list);
1581         }
1582 }
1583
1584
1585 void InsetText::setFont(BufferView * bv, LyXFont const & font, bool toggleall,
1586                         bool selectall)
1587 {
1588         if (the_locking_inset) {
1589                 the_locking_inset->setFont(bv, font, toggleall, selectall);
1590                 return;
1591         }
1592
1593         if ((paragraphs.size() == 1 && paragraphs.begin()->empty())
1594             || cpar()->empty()) {
1595                 text_.setFont(font, toggleall);
1596                 return;
1597         }
1598
1599
1600         if (text_.selection.set())
1601                 recordUndo(bv, Undo::ATOMIC, text_.cursor.par());
1602
1603         if (selectall) {
1604                 text_.cursorTop();
1605                 text_.selection.cursor = text_.cursor;
1606                 text_.cursorBottom();
1607                 text_.setSelection();
1608         }
1609
1610         text_.toggleFree(font, toggleall);
1611
1612         if (selectall)
1613                 text_.clearSelection();
1614
1615         bv->fitCursor();
1616         updateLocal(bv, true);
1617 }
1618
1619
1620 bool InsetText::checkAndActivateInset(BufferView * bv, bool front)
1621 {
1622         InsetOld * inset = cpar()->getInset(cpos());
1623         if (!isHighlyEditableInset(inset))
1624                 return false;
1625         FuncRequest cmd(bv, LFUN_INSET_EDIT, front ? "left" : "right");
1626         inset->localDispatch(cmd);
1627         if (!the_locking_inset)
1628                 return false;
1629         updateLocal(bv, false);
1630         return true;
1631 }
1632
1633
1634 bool InsetText::checkAndActivateInset(BufferView * bv, int x, int y,
1635                                       mouse_button::state button)
1636 {
1637         x -= drawTextXOffset;
1638         int dummyx = x;
1639         int dummyy = y + dim_.asc;
1640         InsetOld * inset = getLyXText(bv)->checkInsetHit(dummyx, dummyy);
1641         // we only do the edit() call if the inset was hit by the mouse
1642         // or if it is a highly editable inset. So we should call this
1643         // function from our own edit with button < 0.
1644         // FIXME: GUII jbl. I've changed this to ::none for now which is probably
1645         // WRONG
1646         if (button == mouse_button::none && !isHighlyEditableInset(inset))
1647                 return false;
1648
1649         if (!inset)
1650                 return false;
1651         if (x < 0)
1652                 x = dim_.wid;
1653         if (y < 0)
1654                 y = dim_.des;
1655         inset_x = cix() - top_x + drawTextXOffset;
1656         inset_y = ciy() + drawTextYOffset;
1657         FuncRequest cmd(bv, LFUN_INSET_EDIT, x - inset_x, y - inset_y, button);
1658         inset->localDispatch(cmd);
1659         if (!the_locking_inset)
1660                 return false;
1661         updateLocal(bv, false);
1662         return true;
1663 }
1664
1665
1666 void InsetText::setParagraphData(ParagraphList const & plist)
1667 {
1668         // we have to unlock any locked inset otherwise we're in troubles
1669         the_locking_inset = 0;
1670
1671         // But it it makes no difference that is a lot better.
1672 #warning FIXME.
1673         // See if this can be simplified when std::list is in effect.
1674         paragraphs.clear();
1675
1676         ParagraphList::const_iterator it = plist.begin();
1677         ParagraphList::const_iterator end = plist.end();
1678         for (; it != end; ++it) {
1679                 paragraphs.push_back(*it);
1680                 paragraphs.back().setInsetOwner(this);
1681         }
1682
1683         reinitLyXText();
1684 }
1685
1686
1687 void InsetText::markNew(bool track_changes)
1688 {
1689         ParagraphList::iterator pit = paragraphs.begin();
1690         ParagraphList::iterator pend = paragraphs.end();
1691         for (; pit != pend; ++pit) {
1692                 if (track_changes) {
1693                         pit->trackChanges();
1694                 } else {
1695                         // no-op when not tracking
1696                         pit->cleanChanges();
1697                 }
1698         }
1699 }
1700
1701
1702 void InsetText::setText(string const & data, LyXFont const & font)
1703 {
1704         clear(false);
1705         for (unsigned int i = 0; i < data.length(); ++i)
1706                 paragraphs.begin()->insertChar(i, data[i], font);
1707         reinitLyXText();
1708 }
1709
1710
1711 void InsetText::setAutoBreakRows(bool flag)
1712 {
1713         if (flag != autoBreakRows) {
1714                 autoBreakRows = flag;
1715                 if (!flag)
1716                         removeNewlines();
1717         }
1718 }
1719
1720
1721 void InsetText::setDrawFrame(BufferView * bv, DrawFrame how)
1722 {
1723         if (how != drawFrame_) {
1724                 drawFrame_ = how;
1725                 updateLocal(bv, false);
1726         }
1727 }
1728
1729
1730 void InsetText::setFrameColor(BufferView * bv, LColor::color col)
1731 {
1732         if (frame_color != col) {
1733                 frame_color = col;
1734                 updateLocal(bv, false);
1735         }
1736 }
1737
1738
1739 int InsetText::cx() const
1740 {
1741         int x = text_.cursor.x() + top_x + TEXT_TO_INSET_OFFSET;
1742         if (the_locking_inset) {
1743                 LyXFont font = text_.getFont(text_.cursor.par(), text_.cursor.pos());
1744                 if (font.isVisibleRightToLeft())
1745                         x -= the_locking_inset->width();
1746         }
1747         return x;
1748 }
1749
1750
1751 int InsetText::cix() const
1752 {
1753         int x = text_.cursor.ix() + top_x + TEXT_TO_INSET_OFFSET;
1754         if (the_locking_inset) {
1755                 LyXFont font = text_.getFont(text_.cursor.par(), text_.cursor.pos());
1756                 if (font.isVisibleRightToLeft())
1757                         x -= the_locking_inset->width();
1758         }
1759         return x;
1760 }
1761
1762
1763 int InsetText::cy() const
1764 {
1765         return text_.cursor.y() - dim_.asc + TEXT_TO_INSET_OFFSET;
1766 }
1767
1768
1769 int InsetText::ciy() const
1770 {
1771         return text_.cursor.iy() - dim_.asc + TEXT_TO_INSET_OFFSET;
1772 }
1773
1774
1775 pos_type InsetText::cpos() const
1776 {
1777         return text_.cursor.pos();
1778 }
1779
1780
1781 ParagraphList::iterator InsetText::cpar() const
1782 {
1783         return text_.cursor.par();
1784 }
1785
1786
1787 bool InsetText::cboundary() const
1788 {
1789         return text_.cursor.boundary();
1790 }
1791
1792
1793 RowList::iterator InsetText::crow() const
1794 {
1795         return text_.cursorRow();
1796 }
1797
1798
1799 LyXText * InsetText::getLyXText(BufferView const * bv,
1800                                 bool const recursive) const
1801 {
1802         setViewCache(bv);
1803         if (recursive && the_locking_inset)
1804                 return the_locking_inset->getLyXText(bv, true);
1805         return &text_;
1806 }
1807
1808
1809 void InsetText::setViewCache(BufferView const * bv) const
1810 {
1811         if (bv)
1812                 text_.bv_owner = const_cast<BufferView *>(bv);
1813 }
1814
1815
1816 void InsetText::deleteLyXText(BufferView * bv, bool recursive) const
1817 {
1818         if (recursive) {
1819                 /// then remove all LyXText in text-insets
1820                 for_each(const_cast<ParagraphList&>(paragraphs).begin(),
1821                          const_cast<ParagraphList&>(paragraphs).end(),
1822                          boost::bind(&Paragraph::deleteInsetsLyXText, _1, bv));
1823         }
1824 }
1825
1826
1827 void InsetText::resizeLyXText(BufferView * bv, bool /*force*/) const
1828 {
1829         if (paragraphs.size() == 1 && paragraphs.begin()->empty())
1830                 return;
1831
1832         if (!bv)
1833                 return;
1834
1835         Assert(bv);
1836         setViewCache(bv);
1837
1838         for_each(const_cast<ParagraphList&>(paragraphs).begin(),
1839                  const_cast<ParagraphList&>(paragraphs).end(),
1840                  boost::bind(&Paragraph::resizeInsetsLyXText, _1, bv));
1841
1842         saveLyXTextState();
1843         text_.init(bv);
1844         restoreLyXTextState();
1845
1846         // seems to be unneeded
1847 #if 1
1848         if (the_locking_inset) {
1849                 inset_x = cix() - top_x + drawTextXOffset;
1850                 inset_y = ciy() + drawTextYOffset;
1851         }
1852
1853         text_.top_y(bv->screen().topCursorVisible(&text_));
1854         if (!owner()) {
1855                 const_cast<InsetText*>(this)->updateLocal(bv, false);
1856                 // this will scroll the screen such that the cursor becomes visible
1857                 bv->updateScrollbar();
1858         }
1859 #endif
1860 }
1861
1862
1863 void InsetText::reinitLyXText() const
1864 {
1865         BufferView * bv = text_.bv_owner;
1866
1867         if (!bv)
1868                 return;
1869
1870         saveLyXTextState();
1871
1872         for_each(const_cast<ParagraphList&>(paragraphs).begin(),
1873                  const_cast<ParagraphList&>(paragraphs).end(),
1874                  boost::bind(&Paragraph::resizeInsetsLyXText, _1, bv));
1875
1876         text_.init(bv);
1877         restoreLyXTextState();
1878         if (the_locking_inset) {
1879                 inset_x = cix() - top_x + drawTextXOffset;
1880                 inset_y = ciy() + drawTextYOffset;
1881         }
1882         text_.top_y(bv->screen().topCursorVisible(&text_));
1883         if (!owner()) {
1884                 // this will scroll the screen such that the cursor becomes visible
1885                 bv->updateScrollbar();
1886         }
1887 }
1888
1889
1890 void InsetText::removeNewlines()
1891 {
1892         bool changed = false;
1893
1894         ParagraphList::iterator it = paragraphs.begin();
1895         ParagraphList::iterator end = paragraphs.end();
1896         for (; it != end; ++it) {
1897                 for (int i = 0; i < it->size(); ++i) {
1898                         if (it->isNewline(i)) {
1899                                 changed = true;
1900                                 it->erase(i);
1901                         }
1902                 }
1903         }
1904         if (changed)
1905                 reinitLyXText();
1906 }
1907
1908
1909 int InsetText::scroll(bool recursive) const
1910 {
1911         int sx = UpdatableInset::scroll(false);
1912
1913         if (recursive && the_locking_inset)
1914                 sx += the_locking_inset->scroll(recursive);
1915
1916         return sx;
1917 }
1918
1919
1920 void InsetText::clearSelection(BufferView * bv)
1921 {
1922         getLyXText(bv)->clearSelection();
1923 }
1924
1925
1926 void InsetText::clearInset(BufferView * bv, int start_x, int baseline) const
1927 {
1928         Painter & pain = bv->painter();
1929         int w = dim_.wid;
1930         int h = dim_.asc + dim_.des;
1931         int ty = baseline - dim_.asc;
1932
1933         if (ty < 0) {
1934                 h += ty;
1935                 ty = 0;
1936         }
1937         if (ty + h > pain.paperHeight())
1938                 h = pain.paperHeight();
1939         if (top_x + drawTextXOffset + w > pain.paperWidth())
1940                 w = pain.paperWidth();
1941         pain.fillRectangle(start_x + 1, ty + 1, w - 3, h - 1, backgroundColor());
1942 }
1943
1944
1945 ParagraphList * InsetText::getParagraphs(int i) const
1946 {
1947         return (i == 0) ? const_cast<ParagraphList*>(&paragraphs) : 0;
1948 }
1949
1950
1951 LyXCursor const & InsetText::cursor(BufferView * bv) const
1952 {
1953         if (the_locking_inset)
1954                 return the_locking_inset->cursor(bv);
1955         return getLyXText(bv)->cursor;
1956 }
1957
1958
1959 InsetOld * InsetText::getInsetFromID(int id_arg) const
1960 {
1961         if (id_arg == id())
1962                 return const_cast<InsetText *>(this);
1963
1964         ParagraphList::const_iterator pit = paragraphs.begin();
1965         ParagraphList::const_iterator pend = paragraphs.end();
1966         for (; pit != pend; ++pit) {
1967                 InsetList::const_iterator it = pit->insetlist.begin();
1968                 InsetList::const_iterator end = pit->insetlist.end();
1969                 for (; it != end; ++it) {
1970                         if (it->inset->id() == id_arg)
1971                                 return it->inset;
1972                         InsetOld * in = it->inset->getInsetFromID(id_arg);
1973                         if (in)
1974                                 return in;
1975                 }
1976         }
1977         return 0;
1978 }
1979
1980
1981 WordLangTuple const
1982 InsetText::selectNextWordToSpellcheck(BufferView * bv, float & value) const
1983 {
1984         WordLangTuple word;
1985         if (the_locking_inset) {
1986                 word = the_locking_inset->selectNextWordToSpellcheck(bv, value);
1987                 if (!word.word().empty()) {
1988                         value += cy();
1989                         return word;
1990                 }
1991                 // we have to go on checking so move cursor to the next char
1992                 text_.cursor.pos(text_.cursor.pos() + 1);
1993         }
1994         word = text_.selectNextWordToSpellcheck(value);
1995         if (word.word().empty())
1996                 bv->unlockInset(const_cast<InsetText *>(this));
1997         else
1998                 value = cy();
1999         return word;
2000 }
2001
2002
2003 void InsetText::selectSelectedWord(BufferView * bv)
2004 {
2005         if (the_locking_inset) {
2006                 the_locking_inset->selectSelectedWord(bv);
2007                 return;
2008         }
2009         getLyXText(bv)->selectSelectedWord();
2010         updateLocal(bv, false);
2011 }
2012
2013
2014 bool InsetText::nextChange(BufferView * bv, lyx::pos_type & length)
2015 {
2016         if (the_locking_inset) {
2017                 if (the_locking_inset->nextChange(bv, length))
2018                         return true;
2019                 text_.cursorRight(true);
2020         }
2021         lyx::find::SearchResult result =
2022                 lyx::find::findNextChange(bv, &text_, length);
2023
2024         if (result == lyx::find::SR_FOUND) {
2025                 LyXCursor cur = text_.cursor;
2026                 bv->unlockInset(bv->theLockingInset());
2027                 if (bv->lockInset(this))
2028                         locked = true;
2029                 text_.cursor = cur;
2030                 text_.setSelectionRange(length);
2031                 updateLocal(bv, false);
2032         }
2033         return result != lyx::find::SR_NOT_FOUND;
2034 }
2035
2036
2037 bool InsetText::searchForward(BufferView * bv, string const & str,
2038                               bool cs, bool mw)
2039 {
2040         if (the_locking_inset) {
2041                 if (the_locking_inset->searchForward(bv, str, cs, mw))
2042                         return true;
2043                 text_.cursorRight(true);
2044         }
2045         lyx::find::SearchResult result =
2046                 lyx::find::find(bv, &text_, str, true, cs, mw);
2047
2048         if (result == lyx::find::SR_FOUND) {
2049                 LyXCursor cur = text_.cursor;
2050                 bv->unlockInset(bv->theLockingInset());
2051                 if (bv->lockInset(this))
2052                         locked = true;
2053                 text_.cursor = cur;
2054                 text_.setSelectionRange(str.length());
2055                 updateLocal(bv, false);
2056         }
2057         return result != lyx::find::SR_NOT_FOUND;
2058 }
2059
2060
2061 bool InsetText::searchBackward(BufferView * bv, string const & str,
2062                                bool cs, bool mw)
2063 {
2064         if (the_locking_inset) {
2065                 if (the_locking_inset->searchBackward(bv, str, cs, mw))
2066                         return true;
2067         }
2068         if (!locked) {
2069                 ParagraphList::iterator pit = paragraphs.begin();
2070                 ParagraphList::iterator pend = paragraphs.end();
2071
2072                 while (boost::next(pit) != pend)
2073                         ++pit;
2074
2075                 text_.setCursor(pit, pit->size());
2076         }
2077         lyx::find::SearchResult result =
2078                 lyx::find::find(bv, &text_, str, false, cs, mw);
2079
2080         if (result == lyx::find::SR_FOUND) {
2081                 LyXCursor cur = text_.cursor;
2082                 bv->unlockInset(bv->theLockingInset());
2083                 if (bv->lockInset(this))
2084                         locked = true;
2085                 text_.cursor = cur;
2086                 text_.setSelectionRange(str.length());
2087                 updateLocal(bv, false);
2088         }
2089         return result != lyx::find::SR_NOT_FOUND;
2090 }
2091
2092
2093 bool InsetText::checkInsertChar(LyXFont & font)
2094 {
2095         return owner() ? owner()->checkInsertChar(font) : true;
2096 }
2097
2098
2099 void InsetText::collapseParagraphs(BufferView * bv)
2100 {
2101         while (paragraphs.size() > 1) {
2102                 ParagraphList::iterator first_par = paragraphs.begin();
2103                 ParagraphList::iterator next_par = boost::next(first_par);
2104                 size_t const first_par_size = first_par->size();
2105
2106                 if (!first_par->empty() &&
2107                     !next_par->empty() &&
2108                     !first_par->isSeparator(first_par_size - 1)) {
2109                         first_par->insertChar(first_par_size, ' ');
2110                 }
2111
2112                 if (text_.selection.set()) {
2113                         if (text_.selection.start.par() == next_par) {
2114                                 text_.selection.start.par(first_par);
2115                                 text_.selection.start.pos(
2116                                         text_.selection.start.pos() + first_par_size);
2117                         }
2118                         if (text_.selection.end.par() == next_par) {
2119                                 text_.selection.end.par(first_par);
2120                                 text_.selection.end.pos(
2121                                         text_.selection.end.pos() + first_par_size);
2122                         }
2123                 }
2124
2125                 mergeParagraph(bv->buffer()->params, paragraphs, first_par);
2126         }
2127         reinitLyXText();
2128 }
2129
2130
2131 void InsetText::getDrawFont(LyXFont & font) const
2132 {
2133         if (!owner())
2134                 return;
2135         owner()->getDrawFont(font);
2136 }
2137
2138
2139 void InsetText::appendParagraphs(Buffer * buffer, ParagraphList & plist)
2140 {
2141 #warning FIXME Check if Changes stuff needs changing here. (Lgb)
2142 // And it probably does. You have to take a look at this John. (Lgb)
2143 #warning John, have a look here. (Lgb)
2144         ParagraphList::iterator pit = plist.begin();
2145         ParagraphList::iterator ins = paragraphs.insert(paragraphs.end(), *pit);
2146         ++pit;
2147         mergeParagraph(buffer->params, paragraphs, boost::prior(ins));
2148
2149         ParagraphList::iterator pend = plist.end();
2150         for (; pit != pend; ++pit)
2151                 paragraphs.push_back(*pit);
2152
2153         reinitLyXText();
2154 }
2155
2156
2157 void InsetText::addPreview(PreviewLoader & loader) const
2158 {
2159         ParagraphList::const_iterator pit = paragraphs.begin();
2160         ParagraphList::const_iterator pend = paragraphs.end();
2161
2162         for (; pit != pend; ++pit) {
2163                 InsetList::const_iterator it  = pit->insetlist.begin();
2164                 InsetList::const_iterator end = pit->insetlist.end();
2165                 for (; it != end; ++it)
2166                         it->inset->addPreview(loader);
2167         }
2168 }