]> git.lyx.org Git - lyx.git/blob - src/BufferView_pimpl.C
rowlist5
[lyx.git] / src / BufferView_pimpl.C
1 /**
2  * \file BufferView_pimpl.C
3  * Copyright 2002 the LyX Team
4  * Read the file COPYING
5  *
6  * \author various
7  */
8
9 #include <config.h>
10
11 #include "BufferView_pimpl.h"
12 #include "bufferlist.h"
13 #include "bufferview_funcs.h"
14 #include "lfuns.h"
15 #include "debug.h"
16 #include "factory.h"
17 #include "FloatList.h"
18 #include "funcrequest.h"
19 #include "gettext.h"
20 #include "intl.h"
21 #include "iterators.h"
22 #include "lyx_cb.h" // added for Dispatch functions
23 #include "lyx_main.h"
24 #include "lyxfind.h"
25 #include "lyxfunc.h"
26 #include "lyxtext.h"
27 #include "lyxrc.h"
28 #include "lyxrow.h"
29 #include "paragraph.h"
30 #include "ParagraphParameters.h"
31 #include "TextCache.h"
32 #include "undo_funcs.h"
33
34 #include "insets/insetfloatlist.h"
35 #include "insets/insetgraphics.h"
36 #include "insets/insetinclude.h"
37 #include "insets/insetref.h"
38 #include "insets/insettext.h"
39
40 #include "frontends/Alert.h"
41 #include "frontends/Dialogs.h"
42 #include "frontends/FileDialog.h"
43 #include "frontends/LyXView.h"
44 #include "frontends/LyXScreenFactory.h"
45 #include "frontends/mouse_state.h"
46 #include "frontends/screen.h"
47 #include "frontends/WorkArea.h"
48 #include "frontends/WorkAreaFactory.h"
49
50 #include "mathed/formulabase.h"
51
52 #include "graphics/Previews.h"
53
54 #include "support/LAssert.h"
55 #include "support/lstrings.h"
56 #include "support/filetools.h"
57
58 #include <boost/bind.hpp>
59 #include <boost/signals/connection.hpp>
60 #include "support/BoostFormat.h"
61
62 #include <unistd.h>
63 #include <sys/wait.h>
64
65
66 using std::vector;
67 using std::find_if;
68 using std::find;
69 using std::pair;
70 using std::endl;
71 using std::make_pair;
72 using std::min;
73
74 using lyx::pos_type;
75
76 extern BufferList bufferlist;
77
78
79 namespace {
80
81 unsigned int const saved_positions_num = 20;
82
83 // All the below connection objects are needed because of a bug in some
84 // versions of GCC (<=2.96 are on the suspects list.) By having and assigning
85 // to these connections we avoid a segfault upon startup, and also at exit.
86 // (Lgb)
87
88 boost::signals::connection dispatchcon;
89 boost::signals::connection timecon;
90 boost::signals::connection doccon;
91 boost::signals::connection resizecon;
92 boost::signals::connection kpresscon;
93 boost::signals::connection selectioncon;
94 boost::signals::connection lostcon;
95
96
97 } // anon namespace
98
99
100 BufferView::Pimpl::Pimpl(BufferView * bv, LyXView * owner,
101              int xpos, int ypos, int width, int height)
102         : bv_(bv), owner_(owner), buffer_(0), cursor_timeout(400),
103           using_xterm_cursor(false)
104 {
105         workarea_.reset(WorkAreaFactory::create(xpos, ypos, width, height));
106         screen_.reset(LyXScreenFactory::create(workarea()));
107
108         // Setup the signals
109         doccon = workarea().scrollDocView
110                 .connect(boost::bind(&BufferView::Pimpl::scrollDocView, this, _1));
111         resizecon = workarea().workAreaResize
112                 .connect(boost::bind(&BufferView::Pimpl::workAreaResize, this));
113         dispatchcon = workarea().dispatch
114                 .connect(boost::bind(&BufferView::Pimpl::workAreaDispatch, this, _1));
115         kpresscon = workarea().workAreaKeyPress
116                 .connect(boost::bind(&BufferView::Pimpl::workAreaKeyPress, this, _1, _2));
117         selectioncon = workarea().selectionRequested
118                 .connect(boost::bind(&BufferView::Pimpl::selectionRequested, this));
119         lostcon = workarea().selectionLost
120                 .connect(boost::bind(&BufferView::Pimpl::selectionLost, this));
121
122         timecon = cursor_timeout.timeout
123                 .connect(boost::bind(&BufferView::Pimpl::cursorToggle, this));
124         cursor_timeout.start();
125         saved_positions.resize(saved_positions_num);
126 }
127
128
129 WorkArea & BufferView::Pimpl::workarea() const
130 {
131         return *workarea_.get();
132 }
133
134
135 LyXScreen & BufferView::Pimpl::screen() const
136 {
137         return *screen_.get();
138 }
139
140
141 Painter & BufferView::Pimpl::painter() const
142 {
143         return workarea().getPainter();
144 }
145
146
147 void BufferView::Pimpl::buffer(Buffer * b)
148 {
149         lyxerr[Debug::INFO] << "Setting buffer in BufferView ("
150                             << b << ')' << endl;
151         if (buffer_) {
152                 buffer_->delUser(bv_);
153
154                 // Put the old text into the TextCache, but
155                 // only if the buffer is still loaded.
156                 // Also set the owner of the test to 0
157                 //              bv_->text->owner(0);
158                 textcache.add(buffer_, workarea().workWidth(), bv_->text);
159                 if (lyxerr.debugging())
160                         textcache.show(lyxerr, "BufferView::buffer");
161
162                 bv_->text = 0;
163         }
164
165         // set current buffer
166         buffer_ = b;
167
168         // if we're quitting lyx, don't bother updating stuff
169         if (quitting)
170                 return;
171
172         // if we are closing the buffer, use the first buffer as current
173         if (!buffer_) {
174                 buffer_ = bufferlist.first();
175         }
176
177         if (buffer_) {
178                 lyxerr[Debug::INFO] << "Buffer addr: " << buffer_ << endl;
179                 buffer_->addUser(bv_);
180
181                 // If we don't have a text object for this, we make one
182                 if (bv_->text == 0) {
183                         resizeCurrentBuffer();
184                 }
185
186                 // FIXME: needed when ?
187                 bv_->text->top_y(screen().topCursorVisible(bv_->text->cursor, bv_->text->top_y()));
188
189                 // Similarly, buffer-dependent dialogs should be updated or
190                 // hidden. This should go here because some dialogs (eg ToC)
191                 // require bv_->text.
192                 owner_->getDialogs().updateBufferDependent(true);
193         } else {
194                 lyxerr[Debug::INFO] << "  No Buffer!" << endl;
195                 owner_->getDialogs().hideBufferDependent();
196
197                 // Also remove all remaining text's from the testcache.
198                 // (there should not be any!) (if there is any it is a
199                 // bug!)
200                 if (lyxerr.debugging())
201                         textcache.show(lyxerr, "buffer delete all");
202                 textcache.clear();
203         }
204
205         repaint();
206         updateScrollbar();
207         owner_->updateMenubar();
208         owner_->updateToolbar();
209         owner_->updateLayoutChoice();
210         owner_->updateWindowTitle();
211
212         if (grfx::Previews::activated() && buffer_)
213                 grfx::Previews::get().generateBufferPreviews(*buffer_);
214 }
215
216
217 bool BufferView::Pimpl::fitCursor()
218 {
219         bool ret;
220
221         if (bv_->theLockingInset()) {
222                 bv_->theLockingInset()->fitInsetCursor(bv_);
223                 ret = true;
224         } else {
225                 ret = screen().fitCursor(bv_->text, bv_);
226         }
227
228         dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
229
230         // We need to always update, in case we did a
231         // paste and we stayed anchored to a row, but
232         // the actual height of the doc changed ...
233         updateScrollbar();
234         return ret;
235 }
236
237
238 void BufferView::Pimpl::redoCurrentBuffer()
239 {
240         lyxerr[Debug::INFO] << "BufferView::redoCurrentBuffer" << endl;
241         if (buffer_ && bv_->text) {
242                 resizeCurrentBuffer();
243                 updateScrollbar();
244                 owner_->updateLayoutChoice();
245                 repaint();
246         }
247 }
248
249
250 int BufferView::Pimpl::resizeCurrentBuffer()
251 {
252         lyxerr[Debug::INFO] << "resizeCurrentBuffer" << endl;
253
254         Paragraph * par = 0;
255         Paragraph * selstartpar = 0;
256         Paragraph * selendpar = 0;
257         UpdatableInset * the_locking_inset = 0;
258
259         pos_type pos = 0;
260         pos_type selstartpos = 0;
261         pos_type selendpos = 0;
262         bool selection = false;
263         bool mark_set  = false;
264
265         owner_->busy(true);
266
267         owner_->message(_("Formatting document..."));
268
269         if (bv_->text) {
270                 par = bv_->text->cursor.par();
271                 pos = bv_->text->cursor.pos();
272                 selstartpar = bv_->text->selection.start.par();
273                 selstartpos = bv_->text->selection.start.pos();
274                 selendpar = bv_->text->selection.end.par();
275                 selendpos = bv_->text->selection.end.pos();
276                 selection = bv_->text->selection.set();
277                 mark_set = bv_->text->selection.mark();
278                 the_locking_inset = bv_->theLockingInset();
279                 buffer_->resizeInsets(bv_);
280                 // I don't think the delete and new are necessary here we just could
281                 // call only init! (Jug 20020419)
282                 delete bv_->text;
283                 bv_->text = new LyXText(bv_);
284                 bv_->text->init(bv_);
285         } else {
286                 // See if we have a text in TextCache that fits
287                 // the new buffer_ with the correct width.
288                 bv_->text = textcache.findFit(buffer_, workarea().workWidth());
289                 if (bv_->text) {
290                         if (lyxerr.debugging()) {
291                                 lyxerr << "Found a LyXText that fits:\n";
292                                 textcache.show(lyxerr, make_pair(buffer_, make_pair(workarea().workWidth(), bv_->text)));
293                         }
294                         // Set the owner of the newly found text
295                         //      bv_->text->owner(bv_);
296                         if (lyxerr.debugging())
297                                 textcache.show(lyxerr, "resizeCurrentBuffer");
298
299                         buffer_->resizeInsets(bv_);
300                 } else {
301                         bv_->text = new LyXText(bv_);
302                         bv_->text->init(bv_);
303                         //buffer_->resizeInsets(bv_);
304                 }
305         }
306
307         if (par) {
308                 bv_->text->selection.set(true);
309                 // At this point just to avoid the Delete-Empty-Paragraph-
310                 // Mechanism when setting the cursor.
311                 bv_->text->selection.mark(mark_set);
312                 if (selection) {
313                         bv_->text->setCursor(selstartpar, selstartpos);
314                         bv_->text->selection.cursor = bv_->text->cursor;
315                         bv_->text->setCursor(selendpar, selendpos);
316                         bv_->text->setSelection();
317                         bv_->text->setCursor(par, pos);
318                 } else {
319                         bv_->text->setCursor(par, pos);
320                         bv_->text->selection.cursor = bv_->text->cursor;
321                         bv_->text->selection.set(false);
322                 }
323                 // remake the inset locking
324                 bv_->theLockingInset(the_locking_inset);
325         }
326
327         bv_->text->top_y(screen().topCursorVisible(bv_->text->cursor, bv_->text->top_y()));
328
329         switchKeyMap();
330         owner_->busy(false);
331
332         updateScrollbar();
333
334         return 0;
335 }
336
337
338 void BufferView::Pimpl::repaint()
339 {
340         // Regenerate the screen.
341         screen().redraw(bv_->text, bv_);
342 }
343
344
345 void BufferView::Pimpl::updateScrollbar()
346 {
347         if (!bv_->text) {
348                 lyxerr[Debug::GUI] << "no text in updateScrollbar" << endl;
349                 workarea().setScrollbarParams(0, 0, 0);
350                 return;
351         }
352
353         LyXText const & t = *bv_->text;
354
355         lyxerr[Debug::GUI] << "Updating scrollbar: h " << t.height << ", top_y() "
356                 << t.top_y() << ", default height " << defaultRowHeight() << endl;
357
358         workarea().setScrollbarParams(t.height, t.top_y(), defaultRowHeight());
359 }
360
361
362 void BufferView::Pimpl::scrollDocView(int value)
363 {
364         lyxerr[Debug::GUI] << "scrollDocView of " << value << endl;
365
366         if (!buffer_)
367                 return;
368
369         screen().draw(bv_->text, bv_, value);
370
371         if (!lyxrc.cursor_follows_scrollbar)
372                 return;
373
374         LyXText * vbt = bv_->text;
375
376         int const height = defaultRowHeight();
377         int const first = static_cast<int>((bv_->text->top_y() + height));
378         int const last = static_cast<int>((bv_->text->top_y() + workarea().workHeight() - height));
379
380         if (vbt->cursor.y() < first)
381                 vbt->setCursorFromCoordinates(0, first);
382         else if (vbt->cursor.y() > last)
383                 vbt->setCursorFromCoordinates(0, last);
384
385         owner_->updateLayoutChoice();
386 }
387
388
389 void BufferView::Pimpl::scroll(int lines)
390 {
391         if (!buffer_) {
392                 return;
393         }
394
395         LyXText const * t = bv_->text;
396         int const line_height = defaultRowHeight();
397
398         // The new absolute coordinate
399         int new_top_y = t->top_y() + lines * line_height;
400
401         // Restrict to a valid value
402         new_top_y = std::min(t->height - 4 * line_height, new_top_y);
403         new_top_y = std::max(0, new_top_y);
404
405         scrollDocView(new_top_y);
406
407         // Update the scrollbar.
408         workarea().setScrollbarParams(t->height, t->top_y(), defaultRowHeight());
409 }
410
411
412 void BufferView::Pimpl::workAreaKeyPress(LyXKeySymPtr key,
413                                          key_modifier::state state)
414 {
415         bv_->owner()->getLyXFunc().processKeySym(key, state);
416 }
417
418
419 void BufferView::Pimpl::selectionRequested()
420 {
421         static string sel;
422
423         if (!available())
424                 return;
425
426         LyXText * text = bv_->getLyXText();
427
428         if (text->selection.set() &&
429                 (!bv_->text->xsel_cache.set() ||
430                  text->selection.start != bv_->text->xsel_cache.start ||
431                  text->selection.end != bv_->text->xsel_cache.end))
432         {
433                 bv_->text->xsel_cache = text->selection;
434                 sel = text->selectionAsString(bv_->buffer(), false);
435         } else if (!text->selection.set()) {
436                 sel = string();
437                 bv_->text->xsel_cache.set(false);
438         }
439         if (!sel.empty()) {
440                 workarea().putClipboard(sel);
441         }
442 }
443
444
445 void BufferView::Pimpl::selectionLost()
446 {
447         if (available()) {
448                 hideCursor();
449                 toggleSelection();
450                 bv_->getLyXText()->clearSelection();
451                 showCursor();
452                 bv_->text->xsel_cache.set(false);
453         }
454 }
455
456
457 void BufferView::Pimpl::workAreaResize()
458 {
459         static int work_area_width;
460         static int work_area_height;
461
462         bool const widthChange = workarea().workWidth() != work_area_width;
463         bool const heightChange = workarea().workHeight() != work_area_height;
464
465         // update from work area
466         work_area_width = workarea().workWidth();
467         work_area_height = workarea().workHeight();
468
469         if (buffer_ != 0) {
470                 if (widthChange) {
471                         // The visible LyXView need a resize
472                         resizeCurrentBuffer();
473
474                         // Remove all texts from the textcache
475                         // This is not _really_ what we want to do. What
476                         // we really want to do is to delete in textcache
477                         // that does not have a BufferView with matching
478                         // width, but as long as we have only one BufferView
479                         // deleting all gives the same result.
480                         if (lyxerr.debugging())
481                                 textcache.show(lyxerr, "Expose delete all");
482                         textcache.clear();
483                         // FIXME: this is already done in resizeCurrentBuffer() ??
484                         buffer_->resizeInsets(bv_);
485                 } else if (heightChange) {
486                         // fitCursor() ensures we don't jump back
487                         // to the start of the document on vertical
488                         // resize
489                         fitCursor();
490                 }
491         }
492
493         if (widthChange || heightChange) {
494                 repaint();
495         }
496
497         // always make sure that the scrollbar is sane.
498         updateScrollbar();
499         owner_->updateLayoutChoice();
500         return;
501 }
502
503
504 void BufferView::Pimpl::update()
505 {
506         if (!bv_->theLockingInset() || !bv_->theLockingInset()->nodraw()) {
507                 screen().update(*bv_);
508                 bv_->text->clearPaint();
509         }
510 }
511
512
513 void BufferView::Pimpl::update(LyXText * text, BufferView::UpdateCodes f)
514 {
515         if (!text->selection.set() && (f & SELECT)) {
516                 text->selection.cursor = text->cursor;
517         }
518
519         text->fullRebreak();
520
521         if (text->inset_owner) {
522                 text->inset_owner->setUpdateStatus(bv_, InsetText::NONE);
523                 updateInset(text->inset_owner);
524         } else {
525                 update();
526         }
527 }
528
529
530 void BufferView::Pimpl::update(BufferView::UpdateCodes f)
531 {
532         LyXText * text = bv_->text;
533
534         if (!text->selection.set() && (f & SELECT)) {
535                 text->selection.cursor = text->cursor;
536         }
537
538         text->fullRebreak();
539
540         if (text->inset_owner) {
541                 text->inset_owner->setUpdateStatus(bv_, InsetText::NONE);
542                 updateInset(text->inset_owner);
543         } else {
544                 update();
545         }
546 }
547
548
549 // Callback for cursor timer
550 void BufferView::Pimpl::cursorToggle()
551 {
552         if (!buffer_) {
553                 cursor_timeout.restart();
554                 return;
555         }
556
557         if (!bv_->theLockingInset()) {
558                 screen().cursorToggle(bv_);
559         } else {
560                 bv_->theLockingInset()->toggleInsetCursor(bv_);
561         }
562
563         cursor_timeout.restart();
564 }
565
566
567 bool BufferView::Pimpl::available() const
568 {
569         if (buffer_ && bv_->text)
570                 return true;
571         return false;
572 }
573
574
575 Change const BufferView::Pimpl::getCurrentChange()
576 {
577         if (!bv_->buffer()->params.tracking_changes)
578                 return Change(Change::UNCHANGED);
579
580         LyXText * t(bv_->getLyXText());
581
582         if (!t->selection.set())
583                 return Change(Change::UNCHANGED);
584
585         LyXCursor const & cur(t->selection.start);
586         return cur.par()->lookupChangeFull(cur.pos());
587 }
588
589
590 void BufferView::Pimpl::beforeChange(LyXText * text)
591 {
592         toggleSelection();
593         text->clearSelection();
594 }
595
596
597 void BufferView::Pimpl::savePosition(unsigned int i)
598 {
599         if (i >= saved_positions_num)
600                 return;
601         saved_positions[i] = Position(buffer_->fileName(),
602                                       bv_->text->cursor.par()->id(),
603                                       bv_->text->cursor.pos());
604         if (i > 0) {
605                 ostringstream str;
606 #if USE_BOOST_FORMAT
607                 str << boost::format(_("Saved bookmark %1$d")) % i;
608 #else
609                 str << _("Saved bookmark ") << i;
610 #endif
611                 owner_->message(STRCONV(str.str()));
612         }
613 }
614
615
616 void BufferView::Pimpl::restorePosition(unsigned int i)
617 {
618         if (i >= saved_positions_num)
619                 return;
620
621         string const fname = saved_positions[i].filename;
622
623         beforeChange(bv_->text);
624
625         if (fname != buffer_->fileName()) {
626                 Buffer * b = bufferlist.exists(fname) ?
627                         bufferlist.getBuffer(fname) :
628                         bufferlist.loadLyXFile(fname); // don't ask, just load it
629                 if (b != 0) buffer(b);
630         }
631
632         Paragraph * par = buffer_->getParFromID(saved_positions[i].par_id);
633         if (!par)
634                 return;
635
636         bv_->text->setCursor(par,
637                              min(par->size(), saved_positions[i].par_pos));
638
639         update(BufferView::SELECT);
640         if (i > 0) {
641                 ostringstream str;
642 #if USE_BOOST_FORMAT
643                 str << boost::format(_("Moved to bookmark %1$d")) % i;
644 #else
645                 str << _("Moved to bookmark ") << i;
646 #endif
647                 owner_->message(STRCONV(str.str()));
648         }
649 }
650
651
652 bool BufferView::Pimpl::isSavedPosition(unsigned int i)
653 {
654         if (i >= saved_positions_num)
655                 return false;
656
657         return !saved_positions[i].filename.empty();
658 }
659
660
661 void BufferView::Pimpl::switchKeyMap()
662 {
663         if (!lyxrc.rtl_support)
664                 return;
665
666         LyXText * text = bv_->getLyXText();
667         if (text->real_current_font.isRightToLeft()
668             && !(bv_->theLockingInset()
669                  && bv_->theLockingInset()->lyxCode() == Inset::ERT_CODE))
670         {
671                 if (owner_->getIntl().keymap == Intl::PRIMARY)
672                         owner_->getIntl().KeyMapSec();
673         } else {
674                 if (owner_->getIntl().keymap == Intl::SECONDARY)
675                         owner_->getIntl().KeyMapPrim();
676         }
677 }
678
679
680 void BufferView::Pimpl::insetUnlock()
681 {
682         if (bv_->theLockingInset()) {
683                 bv_->theLockingInset()->insetUnlock(bv_);
684                 bv_->theLockingInset(0);
685                 finishUndo();
686         }
687 }
688
689
690 void BufferView::Pimpl::showCursor()
691 {
692         if (bv_->theLockingInset())
693                 bv_->theLockingInset()->showInsetCursor(bv_);
694         else
695                 screen().showCursor(bv_->text, bv_);
696 }
697
698
699 void BufferView::Pimpl::hideCursor()
700 {
701         if (!bv_->theLockingInset())
702                 screen().hideCursor();
703 }
704
705
706 void BufferView::Pimpl::toggleSelection(bool b)
707 {
708         if (bv_->theLockingInset())
709                 bv_->theLockingInset()->toggleSelection(bv_, b);
710         screen().toggleSelection(bv_->text, bv_, b);
711 }
712
713
714 void BufferView::Pimpl::toggleToggle()
715 {
716         screen().toggleToggle(bv_->text, bv_);
717 }
718
719
720 void BufferView::Pimpl::center()
721 {
722         LyXText * t = bv_->text;
723
724         beforeChange(t);
725         int const half_height = workarea().workHeight() / 2;
726         int new_y = 0;
727
728         if (t->cursor.y() > half_height) {
729                 new_y = t->cursor.y() - half_height;
730         }
731
732         // FIXME: look at this comment again ...
733
734         // FIXME: can we do this w/o calling screen directly ?
735         // This updates top_y() but means the fitCursor() call
736         // from the update(FITCUR) doesn't realise that we might
737         // have moved (e.g. from GOTOPARAGRAPH), so doesn't cause
738         // the scrollbar to be updated as it should, so we have
739         // to do it manually. Any operation that does a center()
740         // and also might have moved top_y() must make sure to call
741         // updateScrollbar() currently. Never mind that this is a
742         // pretty obfuscated way of updating t->top_y()
743         screen().draw(t, bv_, new_y);
744
745         update(BufferView::SELECT);
746 }
747
748
749 void BufferView::Pimpl::stuffClipboard(string const & stuff) const
750 {
751         workarea().putClipboard(stuff);
752 }
753
754
755 /*
756  * Dispatch functions for actions which can be valid for BufferView->text
757  * and/or InsetText->text!!!
758  */
759
760
761 Inset * BufferView::Pimpl::getInsetByCode(Inset::Code code)
762 {
763 #if 0
764         LyXCursor cursor = bv_->getLyXText()->cursor;
765         Buffer::inset_iterator it =
766                 find_if(Buffer::inset_iterator(
767                         cursor.par(), cursor.pos()),
768                         buffer_->inset_iterator_end(),
769                         lyx::compare_memfun(&Inset::lyxCode, code));
770         return it != buffer_->inset_iterator_end() ? (*it) : 0;
771 #else
772         // Ok, this is a little bit too brute force but it
773         // should work for now. Better infrastructure is comming. (Lgb)
774
775         Buffer * b = bv_->buffer();
776         LyXCursor cursor = bv_->getLyXText()->cursor;
777
778         Buffer::inset_iterator beg = b->inset_iterator_begin();
779         Buffer::inset_iterator end = b->inset_iterator_end();
780
781         bool cursor_par_seen = false;
782
783         for (; beg != end; ++beg) {
784                 if (beg.getPar() == cursor.par()) {
785                         cursor_par_seen = true;
786                 }
787                 if (cursor_par_seen) {
788                         if (beg.getPar() == cursor.par()
789                             && beg.getPos() >= cursor.pos()) {
790                                 break;
791                         } else if (beg.getPar() != cursor.par()) {
792                                 break;
793                         }
794                 }
795
796         }
797         if (beg != end) {
798                 // Now find the first inset that matches code.
799                 for (; beg != end; ++beg) {
800                         if (beg->lyxCode() == code) {
801                                 return &(*beg);
802                         }
803                 }
804         }
805         return 0;
806 #endif
807 }
808
809
810 void BufferView::Pimpl::MenuInsertLyXFile(string const & filen)
811 {
812         string filename = filen;
813
814         if (filename.empty()) {
815                 // Launch a file browser
816                 string initpath = lyxrc.document_path;
817
818                 if (available()) {
819                         string const trypath = owner_->buffer()->filePath();
820                         // If directory is writeable, use this as default.
821                         if (IsDirWriteable(trypath))
822                                 initpath = trypath;
823                 }
824
825                 FileDialog fileDlg(_("Select LyX document to insert"),
826                         LFUN_FILE_INSERT,
827                         make_pair(string(_("Documents|#o#O")),
828                                   string(lyxrc.document_path)),
829                         make_pair(string(_("Examples|#E#e")),
830                                   string(AddPath(system_lyxdir, "examples"))));
831
832                 FileDialog::Result result =
833                         fileDlg.open(initpath,
834                                        _("*.lyx| LyX Documents (*.lyx)"));
835
836                 if (result.first == FileDialog::Later)
837                         return;
838
839                 filename = result.second;
840
841                 // check selected filename
842                 if (filename.empty()) {
843                         owner_->message(_("Canceled."));
844                         return;
845                 }
846         }
847
848         // get absolute path of file and add ".lyx" to the filename if
849         // necessary
850         filename = FileSearch(string(), filename, "lyx");
851
852         string const disp_fn(MakeDisplayPath(filename));
853
854         ostringstream s1;
855 #if USE_BOOST_FORMAT
856         s1 << boost::format(_("Inserting document %1$s...")) % disp_fn;
857 #else
858         s1 << _("Inserting document ") << disp_fn << _("...");
859 #endif
860         owner_->message(STRCONV(s1.str()));
861         bool const res = bv_->insertLyXFile(filename);
862         if (res) {
863                 ostringstream str;
864 #if USE_BOOST_FORMAT
865                 str << boost::format(_("Document %1$s inserted.")) % disp_fn;
866 #else
867                 str << _("Document ") << disp_fn << _(" inserted.");
868 #endif
869                 owner_->message(STRCONV(str.str()));
870         } else {
871                 ostringstream str;
872 #if USE_BOOST_FORMAT
873                 str << boost::format(_("Could not insert document %1$s")) % disp_fn;
874 #else
875                 str << _("Could not insert document ") << disp_fn;
876 #endif
877                 owner_->message(STRCONV(str.str()));
878         }
879 }
880
881
882 void BufferView::Pimpl::trackChanges()
883 {
884         Buffer * buf(bv_->buffer());
885         bool const tracking(buf->params.tracking_changes);
886
887         if (!tracking) {
888                 ParIterator const end = buf->par_iterator_end();
889                 for (ParIterator it = buf->par_iterator_begin(); it != end; ++it) {
890                         (*it)->trackChanges();
891                 }
892                 buf->params.tracking_changes = true;
893
894                 // we cannot allow undos beyond the freeze point
895                 buf->undostack.clear();
896         } else {
897                 update(BufferView::SELECT);
898                 bv_->text->setCursor(&(*buf->paragraphs.begin()), 0);
899 #warning changes FIXME
900                 //moveCursorUpdate(false);
901
902                 bool found = lyxfind::findNextChange(bv_);
903                 if (found) {
904                         owner_->getDialogs().show("changes");
905                         return;
906                 }
907
908                 ParIterator const end = buf->par_iterator_end();
909                 for (ParIterator it = buf->par_iterator_begin(); it != end; ++it) {
910                         (*it)->untrackChanges();
911                 }
912                 buf->params.tracking_changes = false;
913         }
914
915         buf->redostack.clear();
916 }
917
918
919 // Doesn't go through lyxfunc, so we need to update the
920 // layout choice etc. ourselves
921 bool BufferView::Pimpl::workAreaDispatch(FuncRequest const & ev_in)
922 {
923         // e.g. Qt mouse press when no buffer
924         if (!available())
925                 return false;
926
927         bool const res = dispatch(ev_in);
928
929         bv_->owner()->updateLayoutChoice();
930         bv_->fitCursor();
931
932         return res;
933 }
934
935
936 bool BufferView::Pimpl::dispatch(FuncRequest const & ev_in)
937 {
938         // Make sure that the cached BufferView is correct.
939         FuncRequest ev = ev_in;
940         ev.setView(bv_);
941
942         lyxerr[Debug::ACTION] << "BufferView::Pimpl::Dispatch:"
943                 << " action[" << ev.action << ']'
944                 << " arg[" << ev.argument << ']'
945                 << " x[" << ev.x << ']'
946                 << " y[" << ev.y << ']'
947                 << " button[" << ev.button() << ']'
948                 << endl;
949
950         LyXTextClass const & tclass = buffer_->params.getLyXTextClass();
951
952         switch (ev.action) {
953
954         case LFUN_SCROLL_INSET:
955                 // this is not handled here as this function is only active
956                 // if we have a locking_inset and that one is (or contains)
957                 // a tabular-inset
958                 break;
959
960         case LFUN_LAYOUT_COPY:
961                 bv_->copyEnvironment();
962                 break;
963
964         case LFUN_LAYOUT_PASTE:
965                 bv_->pasteEnvironment();
966                 switchKeyMap();
967                 break;
968
969         case LFUN_FILE_INSERT:
970                 MenuInsertLyXFile(ev.argument);
971                 break;
972
973         case LFUN_FILE_INSERT_ASCII_PARA:
974                 InsertAsciiFile(bv_, ev.argument, true);
975                 break;
976
977         case LFUN_FILE_INSERT_ASCII:
978                 InsertAsciiFile(bv_, ev.argument, false);
979                 break;
980
981         case LFUN_LANGUAGE:
982                 lang(bv_, ev.argument);
983                 switchKeyMap();
984                 owner_->view_state_changed();
985                 break;
986
987         case LFUN_EMPH:
988                 emph(bv_);
989                 owner_->view_state_changed();
990                 break;
991
992         case LFUN_BOLD:
993                 bold(bv_);
994                 owner_->view_state_changed();
995                 break;
996
997         case LFUN_NOUN:
998                 noun(bv_);
999                 owner_->view_state_changed();
1000                 break;
1001
1002         case LFUN_CODE:
1003                 code(bv_);
1004                 owner_->view_state_changed();
1005                 break;
1006
1007         case LFUN_SANS:
1008                 sans(bv_);
1009                 owner_->view_state_changed();
1010                 break;
1011
1012         case LFUN_ROMAN:
1013                 roman(bv_);
1014                 owner_->view_state_changed();
1015                 break;
1016
1017         case LFUN_DEFAULT:
1018                 styleReset(bv_);
1019                 owner_->view_state_changed();
1020                 break;
1021
1022         case LFUN_UNDERLINE:
1023                 underline(bv_);
1024                 owner_->view_state_changed();
1025                 break;
1026
1027         case LFUN_FONT_SIZE:
1028                 fontSize(bv_, ev.argument);
1029                 owner_->view_state_changed();
1030                 break;
1031
1032         case LFUN_FONT_STATE:
1033                 owner_->getLyXFunc().setMessage(currentState(bv_));
1034                 break;
1035
1036         case LFUN_INSERT_LABEL: {
1037                 // Try and generate a valid label
1038                 string const contents = ev.argument.empty() ?
1039                         getPossibleLabel(*bv_) : ev.argument;
1040                 InsetCommandParams icp("label", contents);
1041                 string data = InsetCommandMailer::params2string("label", icp);
1042                 owner_->getDialogs().show("label", data, 0);
1043         }
1044         break;
1045
1046         case LFUN_BOOKMARK_SAVE:
1047                 savePosition(strToUnsignedInt(ev.argument));
1048                 break;
1049
1050         case LFUN_BOOKMARK_GOTO:
1051                 restorePosition(strToUnsignedInt(ev.argument));
1052                 break;
1053
1054         case LFUN_REF_GOTO: {
1055                 string label = ev.argument;
1056                 if (label.empty()) {
1057                         InsetRef * inset =
1058                                 static_cast<InsetRef*>(getInsetByCode(Inset::REF_CODE));
1059                         if (inset) {
1060                                 label = inset->getContents();
1061                                 savePosition(0);
1062                         }
1063                 }
1064
1065                 if (!label.empty())
1066                         bv_->gotoLabel(label);
1067         }
1068         break;
1069
1070         // --- accented characters ---------------------------
1071
1072         case LFUN_UMLAUT:
1073         case LFUN_CIRCUMFLEX:
1074         case LFUN_GRAVE:
1075         case LFUN_ACUTE:
1076         case LFUN_TILDE:
1077         case LFUN_CEDILLA:
1078         case LFUN_MACRON:
1079         case LFUN_DOT:
1080         case LFUN_UNDERDOT:
1081         case LFUN_UNDERBAR:
1082         case LFUN_CARON:
1083         case LFUN_SPECIAL_CARON:
1084         case LFUN_BREVE:
1085         case LFUN_TIE:
1086         case LFUN_HUNG_UMLAUT:
1087         case LFUN_CIRCLE:
1088         case LFUN_OGONEK:
1089                 if (ev.argument.empty()) {
1090                         // As always...
1091                         owner_->getLyXFunc().handleKeyFunc(ev.action);
1092                 } else {
1093                         owner_->getLyXFunc().handleKeyFunc(ev.action);
1094                         owner_->getIntl().getTransManager()
1095                                 .TranslateAndInsert(ev.argument[0], bv_->getLyXText());
1096                         update(bv_->getLyXText(), BufferView::SELECT);
1097                 }
1098                 break;
1099
1100         case LFUN_MATH_MACRO:
1101         case LFUN_MATH_DELIM:
1102         case LFUN_INSERT_MATRIX:
1103         case LFUN_INSERT_MATH:
1104         case LFUN_MATH_IMPORT_SELECTION: // Imports LaTeX from the X selection
1105         case LFUN_MATH_DISPLAY:          // Open or create a displayed math inset
1106         case LFUN_MATH_MODE:             // Open or create an inlined math inset
1107                 mathDispatch(ev);
1108                 break;
1109
1110         case LFUN_INSET_APPLY: {
1111                 string const name = ev.getArg(0);
1112
1113                 InsetBase * inset = owner_->getDialogs().getOpenInset(name);
1114                 if (inset) {
1115                         // This works both for 'original' and 'mathed' insets.
1116                         // Note that the localDispatch performs updateInset
1117                         // also.
1118                         FuncRequest fr(bv_, LFUN_INSET_MODIFY, ev.argument);
1119                         inset->localDispatch(fr);
1120                 } else {
1121                         FuncRequest fr(bv_, LFUN_INSET_INSERT, ev.argument);
1122                         dispatch(fr);
1123                 }
1124         }
1125         break;
1126
1127         case LFUN_INSET_INSERT: {
1128                 Inset * inset = createInset(ev);
1129                 if (inset && insertInset(inset)) {
1130                         updateInset(inset);
1131
1132                         string const name = ev.getArg(0);
1133                         if (name == "bibitem") {
1134                                 // We need to do a redraw because the maximum
1135                                 // InsetBibitem width could have changed
1136 #warning please check you mean repaint() not update(),
1137 #warning and whether the repaint() is needed at all
1138                                 bv_->repaint();
1139                                 bv_->fitCursor();
1140                         }
1141                 } else {
1142                         delete inset;
1143                 }
1144         }
1145         break;
1146
1147         case LFUN_FLOAT_LIST:
1148                 if (tclass.floats().typeExist(ev.argument)) {
1149                         Inset * inset = new InsetFloatList(ev.argument);
1150                         if (!insertInset(inset, tclass.defaultLayoutName()))
1151                                 delete inset;
1152                 } else {
1153                         lyxerr << "Non-existent float type: "
1154                                << ev.argument << endl;
1155                 }
1156                 break;
1157
1158         case LFUN_LAYOUT_PARAGRAPH: {
1159                 Paragraph const * par = bv_->getLyXText()->cursor.par();
1160                 if (!par)
1161                         break;
1162
1163                 string data;
1164                 params2string(*par, data);
1165
1166                 data = "show\n" + data;
1167                 bv_->owner()->getDialogs().show("paragraph", data);
1168                 break;
1169         }
1170
1171         case LFUN_PARAGRAPH_UPDATE: {
1172                 Paragraph const * par = bv_->getLyXText()->cursor.par();
1173                 if (!par)
1174                         break;
1175
1176                 string data;
1177                 params2string(*par, data);
1178
1179                 // Will the paragraph accept changes from the dialog?
1180                 Inset * const inset = par->inInset();
1181                 bool const accept =
1182                         !(inset && inset->forceDefaultParagraphs(inset));
1183
1184                 data = "update " + tostr(accept) + '\n' + data;
1185                 bv_->owner()->getDialogs().update("paragraph", data);
1186                 break;
1187         }
1188
1189         case LFUN_PARAGRAPH_APPLY:
1190                 setParagraphParams(*bv_, ev.argument);
1191                 break;
1192
1193         case LFUN_THESAURUS_ENTRY:
1194         {
1195                 string arg = ev.argument;
1196
1197                 if (arg.empty()) {
1198                         arg = bv_->getLyXText()->selectionAsString(buffer_,
1199                                                                    false);
1200
1201                         // FIXME
1202                         if (arg.size() > 100 || arg.empty()) {
1203                                 // Get word or selection
1204                                 bv_->getLyXText()->selectWordWhenUnderCursor(LyXText::WHOLE_WORD);
1205                                 arg = bv_->getLyXText()->selectionAsString(buffer_, false);
1206                                 // FIXME: where is getLyXText()->unselect(bv_) ?
1207                         }
1208                 }
1209
1210                 bv_->owner()->getDialogs().show("thesaurus", arg);
1211         }
1212                 break;
1213
1214         case LFUN_TRACK_CHANGES:
1215                 trackChanges();
1216                 break;
1217
1218         case LFUN_MERGE_CHANGES:
1219                 owner_->getDialogs().show("changes");
1220                 break;
1221
1222         case LFUN_ACCEPT_ALL_CHANGES: {
1223                 update(BufferView::SELECT);
1224                 bv_->text->setCursor(&(*bv_->buffer()->paragraphs.begin()), 0);
1225 #warning FIXME changes
1226                 //moveCursorUpdate(false);
1227
1228                 while (lyxfind::findNextChange(bv_)) {
1229                         bv_->getLyXText()->acceptChange();
1230                 }
1231                 update(BufferView::SELECT);
1232                 break;
1233         }
1234
1235         case LFUN_REJECT_ALL_CHANGES: {
1236                 update(BufferView::SELECT);
1237                 bv_->text->setCursor(&(*bv_->buffer()->paragraphs.begin()), 0);
1238 #warning FIXME changes
1239                 //moveCursorUpdate(false);
1240
1241                 while (lyxfind::findNextChange(bv_)) {
1242                         bv_->getLyXText()->rejectChange();
1243                 }
1244                 update(BufferView::SELECT);
1245                 break;
1246         }
1247
1248         case LFUN_ACCEPT_CHANGE: {
1249                 bv_->getLyXText()->acceptChange();
1250                 update(BufferView::SELECT);
1251                 break;
1252         }
1253
1254         case LFUN_REJECT_CHANGE: {
1255                 bv_->getLyXText()->rejectChange();
1256                 update(BufferView::SELECT);
1257                 break;
1258         }
1259
1260         case LFUN_UNKNOWN_ACTION:
1261                 ev.errorMessage(N_("Unknown function!"));
1262                 break;
1263
1264         default:
1265                 return bv_->getLyXText()->dispatch(FuncRequest(ev, bv_));
1266         } // end of switch
1267
1268         return true;
1269 }
1270
1271
1272 bool BufferView::Pimpl::insertInset(Inset * inset, string const & lout)
1273 {
1274         // if we are in a locking inset we should try to insert the
1275         // inset there otherwise this is a illegal function now
1276         if (bv_->theLockingInset()) {
1277                 if (bv_->theLockingInset()->insetAllowed(inset))
1278                         return bv_->theLockingInset()->insertInset(bv_, inset);
1279                 return false;
1280         }
1281
1282         // not quite sure if we want this...
1283         setCursorParUndo(bv_);
1284         freezeUndo();
1285
1286         beforeChange(bv_->text);
1287         if (!lout.empty()) {
1288                 update(BufferView::SELECT);
1289                 bv_->text->breakParagraph(bv_->buffer()->paragraphs);
1290                 update(BufferView::SELECT);
1291
1292                 if (!bv_->text->cursor.par()->empty()) {
1293                         bv_->text->cursorLeft(bv_);
1294
1295                         bv_->text->breakParagraph(bv_->buffer()->paragraphs);
1296                         update(BufferView::SELECT);
1297                 }
1298
1299                 string lres = lout;
1300                 LyXTextClass const & tclass =
1301                         buffer_->params.getLyXTextClass();
1302                 bool hasLayout = tclass.hasLayout(lres);
1303                 string lay = tclass.defaultLayoutName();
1304
1305                 if (hasLayout != false) {
1306                         // layout found
1307                         lay = lres;
1308                 } else {
1309                         // layout not fount using default
1310                         lay = tclass.defaultLayoutName();
1311                 }
1312
1313                 bv_->text->setLayout(lay);
1314
1315                 bv_->text->setParagraph(0, 0,
1316                                    0, 0,
1317                                    VSpace(VSpace::NONE), VSpace(VSpace::NONE),
1318                                    Spacing(),
1319                                    LYX_ALIGN_LAYOUT,
1320                                    string(),
1321                                    0);
1322                 update(BufferView::SELECT);
1323         }
1324
1325         bv_->text->insertInset(inset);
1326         update(BufferView::SELECT);
1327
1328         unFreezeUndo();
1329         return true;
1330 }
1331
1332
1333 void BufferView::Pimpl::updateInset(Inset * inset)
1334 {
1335         if (!inset || !available())
1336                 return;
1337
1338         // first check for locking insets
1339         if (bv_->theLockingInset()) {
1340                 if (bv_->theLockingInset() == inset) {
1341                         if (bv_->text->updateInset(inset)) {
1342                                 update();
1343                                 updateScrollbar();
1344                                 return;
1345                         }
1346                 } else if (bv_->theLockingInset()->updateInsetInInset(bv_, inset)) {
1347                         if (bv_->text->updateInset(bv_->theLockingInset())) {
1348                                 update();
1349                                 updateScrollbar();
1350                                 return;
1351                         }
1352                 }
1353         }
1354
1355         // then check if the inset is a top_level inset (has no owner)
1356         // if yes do the update as always otherwise we have to update the
1357         // toplevel inset where this inset is inside
1358         Inset * tl_inset = inset;
1359         while (tl_inset->owner())
1360                 tl_inset = tl_inset->owner();
1361         hideCursor();
1362         if (tl_inset == inset) {
1363                 update(BufferView::UPDATE);
1364                 if (bv_->text->updateInset(inset)) {
1365                         update(BufferView::SELECT);
1366                         return;
1367                 }
1368         } else if (static_cast<UpdatableInset *>(tl_inset)
1369                            ->updateInsetInInset(bv_, inset))
1370         {
1371                 if (bv_->text->updateInset(tl_inset)) {
1372                         update();
1373                         updateScrollbar();
1374                 }
1375         }
1376 }