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