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