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