]> git.lyx.org Git - lyx.git/blob - src/BufferView_pimpl.C
This commit moves the busy cursor and formatting message handling from BufferView...
[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 Braunstein
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  * \author Abdelrazak Younes
16  *
17  * Full author contact details are available in file CREDITS.
18  */
19
20 #include <config.h>
21
22 #include "BufferView_pimpl.h"
23 #include "buffer.h"
24 #include "buffer_funcs.h"
25 #include "bufferlist.h"
26 #include "bufferparams.h"
27 #include "coordcache.h"
28 #include "cursor.h"
29 #include "CutAndPaste.h"
30 #include "debug.h"
31 #include "dispatchresult.h"
32 #include "errorlist.h"
33 #include "factory.h"
34 #include "FloatList.h"
35 #include "funcrequest.h"
36 #include "FuncStatus.h"
37 #include "gettext.h"
38 #include "intl.h"
39 #include "insetiterator.h"
40 #include "LaTeXFeatures.h"
41 #include "lyx_cb.h" // added for Dispatch functions
42 #include "lyx_main.h"
43 #include "lyxfind.h"
44 #include "lyxfunc.h"
45 #include "lyxtext.h"
46 #include "lyxrc.h"
47 #include "session.h"
48 #include "metricsinfo.h"
49 #include "paragraph.h"
50 #include "paragraph_funcs.h"
51 #include "ParagraphParameters.h"
52 #include "pariterator.h"
53 #include "toc.h"
54 #include "undo.h"
55 #include "vspace.h"
56
57 #include "insets/insetbibtex.h"
58 #include "insets/insetref.h"
59 #include "insets/insettext.h"
60
61 #include "frontends/Alert.h"
62 #include "frontends/Dialogs.h"
63 #include "frontends/FileDialog.h"
64 #include "frontends/font_metrics.h"
65 #include "frontends/Gui.h"
66 #include "frontends/LyXView.h"
67 #include "frontends/Selection.h"
68
69 #include "graphics/Previews.h"
70
71 #include "support/convert.h"
72 #include "support/filefilterlist.h"
73 #include "support/filetools.h"
74 #include "support/package.h"
75 #include "support/types.h"
76
77 #include <boost/bind.hpp>
78 #include <boost/current_function.hpp>
79
80 #include <functional>
81 #include <vector>
82
83 using lyx::frontend::Clipboard;
84 using lyx::frontend::Gui;
85
86 using lyx::pos_type;
87
88 using lyx::support::addPath;
89 using lyx::support::bformat;
90 using lyx::support::FileFilterList;
91 using lyx::support::fileSearch;
92 using lyx::support::isDirWriteable;
93 using lyx::support::makeDisplayPath;
94 using lyx::support::makeAbsPath;
95 using lyx::support::package;
96
97 using std::endl;
98 using std::istringstream;
99 using std::make_pair;
100 using std::min;
101 using std::max;
102 using std::string;
103 using std::mem_fun_ref;
104 using std::vector;
105
106 extern BufferList bufferlist;
107
108
109 namespace {
110
111 unsigned int const saved_positions_num = 20;
112
113
114 /// Return an inset of this class if it exists at the current cursor position
115 template <class T>
116 T * getInsetByCode(LCursor & cur, InsetBase::Code code)
117 {
118         T * inset = 0;
119         DocIterator it = cur;
120         if (it.nextInset() &&
121             it.nextInset()->lyxCode() == code) {
122                 inset = static_cast<T*>(it.nextInset());
123         }
124         return inset;
125 }
126
127 } // anon namespace
128
129
130 BufferView::Pimpl::Pimpl(BufferView & bv, LyXView * owner)
131         : bv_(&bv), owner_(owner), buffer_(0), wh_(0),
132           cursor_(bv),
133           multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0)
134 {
135         xsel_cache_.set = false;
136
137         saved_positions.resize(saved_positions_num);
138         // load saved bookmarks
139         lyx::Session::BookmarkList & bmList = LyX::ref().session().loadBookmarks();
140         for (lyx::Session::BookmarkList::iterator bm = bmList.begin();
141                 bm != bmList.end(); ++bm)
142                 if (bm->get<0>() < saved_positions_num)
143                         saved_positions[bm->get<0>()] = Position( bm->get<1>(), bm->get<2>(), bm->get<3>() );
144         // and then clear them
145         bmList.clear();
146 }
147
148
149 bool BufferView::Pimpl::loadLyXFile(string const & filename, bool tolastfiles)
150 {
151         // Get absolute path of file and add ".lyx"
152         // to the filename if necessary
153         string s = fileSearch(string(), filename, "lyx");
154
155         bool const found = !s.empty();
156
157         if (!found)
158                 s = filename;
159
160         // File already open?
161         if (bufferlist.exists(s)) {
162                 string const file = makeDisplayPath(s, 20);
163                 string text = bformat(_("The document %1$s is already "
164                                         "loaded.\n\nDo you want to revert "
165                                         "to the saved version?"), file);
166                 int const ret = Alert::prompt(_("Revert to saved document?"),
167                         text, 0, 1,  _("&Revert"), _("&Switch to document"));
168
169                 if (ret != 0) {
170                         setBuffer(bufferlist.getBuffer(s));
171                         return true;
172                 }
173                 // FIXME: should be LFUN_REVERT
174                 if (!bufferlist.close(bufferlist.getBuffer(s), false))
175                         return false;
176                 // Fall through to new load. (Asger)
177         }
178
179         Buffer * b = 0;
180
181         if (found) {
182                 b = bufferlist.newBuffer(s);
183                 if (!::loadLyXFile(b, s)) {
184                         bufferlist.release(b);
185                         return false;
186                 }
187         } else {
188                 string text = bformat(_("The document %1$s does not yet "
189                                         "exist.\n\nDo you want to create "
190                                         "a new document?"), s);
191                 int const ret = Alert::prompt(_("Create new document?"),
192                          text, 0, 1, _("&Create"), _("Cancel"));
193
194                 if (ret == 0) {
195                         b = newFile(s, string(), true);
196                         if (!b)
197                                 return false;
198                 } else
199                         return false;
200         }
201
202         setBuffer(b);
203         // Send the "errors" signal in case of parsing errors
204         b->errors("Parse");
205
206         // scroll to the position when the file was last closed
207         if (lyxrc.use_lastfilepos) {
208                 lyx::pit_type pit;
209                 lyx::pos_type pos;
210                 boost::tie(pit, pos) = LyX::ref().session().loadFilePosition(s);
211                 // I am not sure how to separate the following part to a function
212                 // so I will leave this to Lars.
213                 //
214                 // check pit since the document may be externally changed.
215                 if ( static_cast<size_t>(pit) < b->paragraphs().size() ) {
216                         ParIterator it = b->par_iterator_begin();
217                         ParIterator const end = b->par_iterator_end();
218                         for (; it != end; ++it)
219                                 if (it.pit() == pit) {
220                                         // restored pos may be bigger than it->size
221                                         bv_->setCursor(makeDocIterator(it, min(pos, it->size())));
222                                         bv_->update(Update::FitCursor);
223                                         break;
224                                 }
225                 }
226         }
227
228         if (tolastfiles)
229                 LyX::ref().session().addLastFile(b->fileName());
230
231         return true;
232 }
233
234
235 int BufferView::Pimpl::width() const
236 {
237         return width_;
238 }
239
240
241 int BufferView::Pimpl::height() const
242 {
243         return height_;
244 }
245
246
247 void BufferView::Pimpl::setBuffer(Buffer * b)
248 {
249         lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
250                             << "[ b = " << b << "]" << endl;
251
252         if (buffer_) {
253                 // Save the actual cursor position and anchor inside the
254                 // buffer so that it can be restored in case we rechange
255                 // to this buffer later on.
256                 buffer_->saveCursor(cursor_.selectionBegin(),
257                                     cursor_.selectionEnd());
258                 // current buffer is going to be switched-off, save cursor pos
259                 LyX::ref().session().saveFilePosition(buffer_->fileName(),
260                         boost::tie(cursor_.pit(), cursor_.pos()) );
261         }
262
263         // If we are closing current buffer, switch to the first in
264         // buffer list.
265         if (!b) {
266                 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
267                                     << " No Buffer!" << endl;
268                 // We are closing the buffer, use the first buffer as current
269                 buffer_ = bufferlist.first();
270         } else {
271                 // Set current buffer
272                 buffer_ = b;
273         }
274
275         // Reset old cursor
276         cursor_ = LCursor(*bv_);
277         anchor_ref_ = 0;
278         offset_ref_ = 0;
279
280         // If we're quitting lyx, don't bother updating stuff
281         if (quitting)
282                 return;
283
284         if (buffer_) {
285                 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
286                                     << "Buffer addr: " << buffer_ << endl;
287                 cursor_.push(buffer_->inset());
288                 cursor_.resetAnchor();
289                 buffer_->text().init(bv_);
290                 buffer_->text().setCurrentFont(cursor_);
291                 if (buffer_->getCursor().size() > 0 &&
292                     buffer_->getAnchor().size() > 0)
293                 {
294                         cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
295                         cursor_.resetAnchor();
296                         cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
297                         cursor_.setSelection();
298                 }
299         }
300
301         update();
302
303         if (buffer_ && lyx::graphics::Previews::status() != LyXRC::PREVIEW_OFF)
304                 lyx::graphics::Previews::get().generateBufferPreviews(*buffer_);
305 }
306
307 string BufferView::Pimpl::firstLayout()
308 {
309         string firstlayout;
310
311         // This is done after the layout combox has been populated
312         if (buffer_) {
313                 size_t i = cursor_.depth() - 1;
314                 // we know we'll eventually find a paragraph
315                 while (true) {
316                         CursorSlice const & slice = cursor_[i];
317                         if (!slice.inset().inMathed()) {
318                                 LyXLayout_ptr const layout = slice.paragraph().layout();
319                                 firstlayout = layout->name();
320                                 break;
321                         }
322                         BOOST_ASSERT(i>0);
323                         --i;
324                 }
325         }
326         return firstlayout;
327 }
328
329
330 void BufferView::Pimpl::resizeCurrentBuffer()
331 {
332         lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
333
334         LyXText * text = bv_->text();
335         if (!text)
336                 return;
337
338         text->init(bv_);
339         update();
340         switchKeyMap();
341 }
342
343
344 void BufferView::Pimpl::updateScrollbar()
345 {
346         if (!bv_->text()) {
347                 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
348                                      << " no text in updateScrollbar" << endl;
349                 scrollbarParameters_.reset();
350                 return;
351         }
352
353         LyXText & t = *bv_->text();
354         int const parsize = int(t.paragraphs().size() - 1);
355         if (anchor_ref_ >  parsize)  {
356                 anchor_ref_ = parsize;
357                 offset_ref_ = 0;
358         }
359
360         lyxerr[Debug::GUI]
361                 << BOOST_CURRENT_FUNCTION
362                 << " Updating scrollbar: height: " << t.paragraphs().size()
363                 << " curr par: " << cursor_.bottom().pit()
364                 << " default height " << defaultRowHeight() << endl;
365
366         // It would be better to fix the scrollbar to understand
367         // values in [0..1] and divide everything by wh
368
369         // estimated average paragraph height:
370         if (wh_ == 0)
371                 wh_ = height_ / 4;
372         int h = t.getPar(anchor_ref_).height();
373
374         // Normalize anchor/offset (MV):
375         while (offset_ref_ > h && anchor_ref_ < parsize) {
376                 anchor_ref_++;
377                 offset_ref_ -= h;
378                 h = t.getPar(anchor_ref_).height();
379         }
380         // Look at paragraph heights on-screen
381         int sumh = 0;
382         int nh = 0;
383         for (lyx::pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
384                 if (sumh > height_)
385                         break;
386                 int const h2 = t.getPar(pit).height();
387                 sumh += h2;
388                 nh++;
389         }
390         int const hav = sumh / nh;
391         // More realistic average paragraph height
392         if (hav > wh_)
393                 wh_ = hav;
394
395         scrollbarParameters_.height = (parsize + 1) * wh_;
396         scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
397         scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
398 }
399
400
401 ScrollbarParameters const & BufferView::Pimpl::scrollbarParameters() const
402 {
403         return scrollbarParameters_;
404 }
405
406
407 void BufferView::Pimpl::scrollDocView(int value)
408 {
409         lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
410                            << "[ value = " << value << "]" << endl;
411
412         if (!buffer_)
413                 return;
414
415         LyXText & t = *bv_->text();
416
417         float const bar = value / float(wh_ * t.paragraphs().size());
418
419         anchor_ref_ = int(bar * t.paragraphs().size());
420         if (anchor_ref_ >  int(t.paragraphs().size()) - 1)
421                 anchor_ref_ = int(t.paragraphs().size()) - 1;
422         t.redoParagraph(anchor_ref_);
423         int const h = t.getPar(anchor_ref_).height();
424         offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
425 }
426
427
428 void BufferView::Pimpl::setCursorFromScrollbar()
429 {
430         LyXText & t = *bv_->text();
431
432         int const height = 2 * defaultRowHeight();
433         int const first = height;
434         int const last = height_ - height;
435         LCursor & cur = cursor_;
436
437         bv_funcs::CurStatus st = bv_funcs::status(bv_, cur);
438
439         switch (st) {
440         case bv_funcs::CUR_ABOVE:
441                 t.setCursorFromCoordinates(cur, 0, first);
442                 cur.clearSelection();
443                 break;
444         case bv_funcs::CUR_BELOW:
445                 t.setCursorFromCoordinates(cur, 0, last);
446                 cur.clearSelection();
447                 break;
448         case bv_funcs::CUR_INSIDE:
449                 int const y = bv_funcs::getPos(cur, cur.boundary()).y_;
450                 int const newy = min(last, max(y, first));
451                 if (y != newy) {
452                         cur.reset(buffer_->inset());
453                         t.setCursorFromCoordinates(cur, 0, newy);
454                 }
455         }
456 }
457
458
459 void BufferView::Pimpl::scroll(int /*lines*/)
460 {
461 //      if (!buffer_)
462 //              return;
463 //
464 //      LyXText const * t = bv_->text();
465 //      int const line_height = defaultRowHeight();
466 //
467 //      // The new absolute coordinate
468 //      int new_top_y = top_y() + lines * line_height;
469 //
470 //      // Restrict to a valid value
471 //      new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
472 //      new_top_y = std::max(0, new_top_y);
473 //
474 //      scrollDocView(new_top_y);
475 //
476 //      // Update the scrollbar.
477 //      workArea_->setScrollbarParams(t->height(), top_y(), defaultRowHeight());}
478 }
479
480
481 void BufferView::Pimpl::selectionRequested()
482 {
483         static string sel;
484
485         if (!available())
486                 return;
487
488         LCursor & cur = cursor_;
489
490         if (!cur.selection()) {
491                 xsel_cache_.set = false;
492                 return;
493         }
494
495         if (!xsel_cache_.set ||
496             cur.top() != xsel_cache_.cursor ||
497             cur.anchor_.top() != xsel_cache_.anchor)
498         {
499                 xsel_cache_.cursor = cur.top();
500                 xsel_cache_.anchor = cur.anchor_.top();
501                 xsel_cache_.set = cur.selection();
502                 sel = cur.selectionAsString(false);
503                 if (!sel.empty())
504                         owner_->gui().selection().put(sel);
505         }
506 }
507
508
509 void BufferView::Pimpl::selectionLost()
510 {
511         if (available()) {
512                 cursor_.clearSelection();
513                 xsel_cache_.set = false;
514         }
515 }
516
517
518 void BufferView::Pimpl::workAreaResize(int width, int height)
519 {
520         bool const widthChange = width != width_;
521         bool const heightChange = height != height_;
522
523         // Update from work area
524         width_ = width;
525         height_ = height;
526
527         if (buffer_ && widthChange) {
528                 // The WorkArea content needs a resize
529                 resizeCurrentBuffer();
530         }
531
532         if (widthChange || heightChange)
533                 update();
534 }
535
536
537 bool BufferView::Pimpl::fitCursor()
538 {
539         if (bv_funcs::status(bv_, cursor_) == bv_funcs::CUR_INSIDE) {
540                 LyXFont const font = cursor_.getFont();
541                 int const asc = font_metrics::maxAscent(font);
542                 int const des = font_metrics::maxDescent(font);
543                 Point const p = bv_funcs::getPos(cursor_, cursor_.boundary());
544                 if (p.y_ - asc >= 0 && p.y_ + des < height_)
545                         return false;
546         }
547         center();
548         return true;
549 }
550
551
552 bool BufferView::Pimpl::multiParSel()
553 {
554         if (!cursor_.selection())
555                 return false;
556         bool ret = multiparsel_cache_;
557         multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
558         // Either this, or previous selection spans paragraphs
559         return ret || multiparsel_cache_;
560 }
561
562
563 ViewMetricsInfo const & BufferView::Pimpl::viewMetricsInfo()
564 {
565         return metrics_info_;
566 }
567
568
569 bool BufferView::Pimpl::update(Update::flags flags)
570 {
571         // This is close to a hot-path.
572         if (lyxerr.debugging(Debug::DEBUG)) {
573                 lyxerr[Debug::DEBUG]
574                         << BOOST_CURRENT_FUNCTION
575                         << "[fitcursor = " << (flags & Update::FitCursor)
576                         << ", forceupdate = " << (flags & Update::Force)
577                         << ", singlepar = " << (flags & Update::SinglePar)
578                         << "]  buffer: " << buffer_ << endl;
579         }
580
581         // Check needed to survive LyX startup
582         if (!buffer_)
583                 return false;
584
585         // Update macro store
586         buffer_->buildMacros();
587
588         // First drawing step
589         updateMetrics(flags & Update::SinglePar);
590
591         // The second drawing step is done in WorkArea::redraw() if needed.
592         bool const need_second_step =
593                 (flags & (Update::Force | Update::FitCursor | Update::MultiParSel))
594                 && (fitCursor() || multiParSel());
595
596         return need_second_step;
597 }
598
599
600 bool BufferView::Pimpl::available() const
601 {
602         return buffer_ && bv_->text();
603 }
604
605
606 Change const BufferView::Pimpl::getCurrentChange()
607 {
608         if (!buffer_->params().tracking_changes)
609                 return Change(Change::UNCHANGED);
610
611         LyXText * text = bv_->getLyXText();
612         LCursor & cur = cursor_;
613
614         if (!cur.selection())
615                 return Change(Change::UNCHANGED);
616
617         return text->getPar(cur.selBegin().pit()).
618                         lookupChange(cur.selBegin().pos());
619 }
620
621
622 void BufferView::Pimpl::savePosition(unsigned int i)
623 {
624         if (i >= saved_positions_num)
625                 return;
626         BOOST_ASSERT(cursor_.inTexted());
627         saved_positions[i] = Position(buffer_->fileName(),
628                                       cursor_.paragraph().id(),
629                                       cursor_.pos());
630         if (i > 0)
631                 owner_->message(bformat(_("Saved bookmark %1$d"), i));
632 }
633
634
635 void BufferView::Pimpl::restorePosition(unsigned int i)
636 {
637         if (i >= saved_positions_num)
638                 return;
639
640         string const fname = saved_positions[i].filename;
641
642         cursor_.clearSelection();
643
644         if (fname != buffer_->fileName()) {
645                 Buffer * b = 0;
646                 if (bufferlist.exists(fname))
647                         b = bufferlist.getBuffer(fname);
648                 else {
649                         b = bufferlist.newBuffer(fname);
650                         // Don't ask, just load it
651                         ::loadLyXFile(b, fname);
652                 }
653                 if (b)
654                         setBuffer(b);
655         }
656
657         ParIterator par = buffer_->getParFromID(saved_positions[i].par_id);
658         if (par == buffer_->par_iterator_end())
659                 return;
660
661         bv_->setCursor(makeDocIterator(par, min(par->size(), saved_positions[i].par_pos)));
662
663         if (i > 0)
664                 owner_->message(bformat(_("Moved to bookmark %1$d"), i));
665 }
666
667
668 bool BufferView::Pimpl::isSavedPosition(unsigned int i)
669 {
670         return i < saved_positions_num && !saved_positions[i].filename.empty();
671 }
672
673
674 void BufferView::Pimpl::saveSavedPositions()
675 {
676         // save bookmarks. It is better to use the pit interface
677         // but I do not know how to effectively convert between
678         // par_id and pit.
679         for (unsigned int i=1; i < saved_positions_num; ++i) {
680                 if ( isSavedPosition(i) )
681                         LyX::ref().session().saveBookmark( boost::tie(
682                                 i,
683                                 saved_positions[i].filename,
684                                 saved_positions[i].par_id,
685                                 saved_positions[i].par_pos) );
686         }
687 }
688
689
690 void BufferView::Pimpl::switchKeyMap()
691 {
692         if (!lyxrc.rtl_support)
693                 return;
694
695         Intl & intl = owner_->getIntl();
696         if (bv_->getLyXText()->real_current_font.isRightToLeft()) {
697                 if (intl.keymap == Intl::PRIMARY)
698                         intl.keyMapSec();
699         } else {
700                 if (intl.keymap == Intl::SECONDARY)
701                         intl.keyMapPrim();
702         }
703 }
704
705
706 void BufferView::Pimpl::center()
707 {
708         CursorSlice & bot = cursor_.bottom();
709         lyx::pit_type const pit = bot.pit();
710         bot.text()->redoParagraph(pit);
711         Paragraph const & par = bot.text()->paragraphs()[pit];
712         anchor_ref_ = pit;
713         offset_ref_ = bv_funcs::coordOffset(cursor_, cursor_.boundary()).y_
714                 + par.ascent() - height_ / 2;
715 }
716
717
718 void BufferView::Pimpl::menuInsertLyXFile(string const & filenm)
719 {
720         BOOST_ASSERT(cursor_.inTexted());
721         string filename = filenm;
722
723         if (filename.empty()) {
724                 // Launch a file browser
725                 string initpath = lyxrc.document_path;
726
727                 if (available()) {
728                         string const trypath = buffer_->filePath();
729                         // If directory is writeable, use this as default.
730                         if (isDirWriteable(trypath))
731                                 initpath = trypath;
732                 }
733
734                 FileDialog fileDlg(_("Select LyX document to insert"),
735                         LFUN_FILE_INSERT,
736                         make_pair(string(_("Documents|#o#O")),
737                                   string(lyxrc.document_path)),
738                         make_pair(string(_("Examples|#E#e")),
739                                   string(addPath(package().system_support(), "examples"))));
740
741                 FileDialog::Result result =
742                         fileDlg.open(initpath,
743                                      FileFilterList(_("LyX Documents (*.lyx)")),
744                                      string());
745
746                 if (result.first == FileDialog::Later)
747                         return;
748
749                 filename = result.second;
750
751                 // check selected filename
752                 if (filename.empty()) {
753                         owner_->message(_("Canceled."));
754                         return;
755                 }
756         }
757
758         // Get absolute path of file and add ".lyx"
759         // to the filename if necessary
760         filename = fileSearch(string(), filename, "lyx");
761
762         string const disp_fn = makeDisplayPath(filename);
763         owner_->message(bformat(_("Inserting document %1$s..."), disp_fn));
764
765         string res;
766         Buffer buf("", false);
767         if (::loadLyXFile(&buf, makeAbsPath(filename))) {
768                 ErrorList & el = buffer_->errorList("Parse");
769                 // Copy the inserted document error list into the current buffer one.
770                 el = buf.errorList("Parse");
771                 lyx::cap::pasteParagraphList(cursor_, buf.paragraphs(),
772                                              buf.params().textclass, el);
773                 res = _("Document %1$s inserted.");
774         } else
775                 res = _("Could not insert document %1$s");
776
777         owner_->message(bformat(res, disp_fn));
778         buffer_->errors("Parse");
779         resizeCurrentBuffer();
780 }
781
782
783 void BufferView::Pimpl::trackChanges()
784 {
785         bool const tracking = buffer_->params().tracking_changes;
786
787         if (!tracking) {
788                 for_each(buffer_->par_iterator_begin(),
789                          buffer_->par_iterator_end(),
790                          bind(&Paragraph::trackChanges, _1, Change::UNCHANGED));
791                 buffer_->params().tracking_changes = true;
792
793                 // We cannot allow undos beyond the freeze point
794                 buffer_->undostack().clear();
795         } else {
796                 cursor_.setCursor(doc_iterator_begin(buffer_->inset()));
797                 if (lyx::find::findNextChange(bv_)) {
798                         owner_->getDialogs().show("changes");
799                         return;
800                 }
801
802                 for_each(buffer_->par_iterator_begin(),
803                          buffer_->par_iterator_end(),
804                          mem_fun_ref(&Paragraph::untrackChanges));
805
806                 buffer_->params().tracking_changes = false;
807         }
808
809         buffer_->redostack().clear();
810 }
811
812
813 bool BufferView::Pimpl::workAreaDispatch(FuncRequest const & cmd0)
814 {
815         //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
816
817         // This is only called for mouse related events including
818         // LFUN_FILE_OPEN generated by drag-and-drop.
819         FuncRequest cmd = cmd0;
820
821         if (!buffer_)
822                 return false;
823
824         LCursor cur(*bv_);
825         cur.push(buffer_->inset());
826         cur.selection() = cursor_.selection();
827
828         // Doesn't go through lyxfunc, so we need to update
829         // the layout choice etc. ourselves
830
831         // E.g. Qt mouse press when no buffer
832         if (!available())
833                 return false;
834
835         // Either the inset under the cursor or the
836         // surrounding LyXText will handle this event.
837
838         // Build temporary cursor.
839         cmd.y = min(max(cmd.y, -1), height_);
840         InsetBase * inset = bv_->text()->editXY(cur, cmd.x, cmd.y);
841         //lyxerr << BOOST_CURRENT_FUNCTION
842         //       << " * hit inset at tip: " << inset << endl;
843         //lyxerr << BOOST_CURRENT_FUNCTION
844         //       << " * created temp cursor:" << cur << endl;
845
846         // Put anchor at the same position.
847         cur.resetAnchor();
848
849         // Try to dispatch to an non-editable inset near this position
850         // via the temp cursor. If the inset wishes to change the real
851         // cursor it has to do so explicitly by using
852         //  cur.bv().cursor() = cur;  (or similar)
853         if (inset)
854                 inset->dispatch(cur, cmd);
855
856         // Now dispatch to the temporary cursor. If the real cursor should
857         // be modified, the inset's dispatch has to do so explicitly.
858         if (!cur.result().dispatched())
859                 cur.dispatch(cmd);
860
861         if (cur.result().dispatched()) {
862                 // Redraw if requested or necessary.
863                 if (cur.result().update())
864                         update(Update::FitCursor | Update::Force);
865                 else
866                         update(Update::FitCursor | Update::MultiParSel);
867         }
868
869         return true;
870 }
871
872
873 FuncStatus BufferView::Pimpl::getStatus(FuncRequest const & cmd)
874 {
875         FuncStatus flag;
876
877         switch (cmd.action) {
878
879         case LFUN_UNDO:
880                 flag.enabled(!buffer_->undostack().empty());
881                 break;
882         case LFUN_REDO:
883                 flag.enabled(!buffer_->redostack().empty());
884                 break;
885         case LFUN_FILE_INSERT:
886         case LFUN_FILE_INSERT_ASCII_PARA:
887         case LFUN_FILE_INSERT_ASCII:
888         case LFUN_BOOKMARK_SAVE:
889                 // FIXME: Actually, these LFUNS should be moved to LyXText
890                 flag.enabled(cursor_.inTexted());
891                 break;
892         case LFUN_FONT_STATE:
893         case LFUN_LABEL_INSERT:
894         case LFUN_PARAGRAPH_GOTO:
895         // FIXME handle non-trivially
896         case LFUN_OUTLINE_UP:
897         case LFUN_OUTLINE_DOWN:
898         case LFUN_OUTLINE_IN:
899         case LFUN_OUTLINE_OUT:
900         case LFUN_NOTE_NEXT:
901         case LFUN_REFERENCE_NEXT:
902         case LFUN_WORD_FIND:
903         case LFUN_WORD_REPLACE:
904         case LFUN_MARK_OFF:
905         case LFUN_MARK_ON:
906         case LFUN_MARK_TOGGLE:
907         case LFUN_SCREEN_RECENTER:
908         case LFUN_BIBTEX_DATABASE_ADD:
909         case LFUN_BIBTEX_DATABASE_DEL:
910         case LFUN_WORDS_COUNT:
911         case LFUN_NEXT_INSET_TOGGLE:
912                 flag.enabled(true);
913                 break;
914
915         case LFUN_LABEL_GOTO: {
916                 flag.enabled(!cmd.argument.empty()
917                     || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
918                 break;
919         }
920
921         case LFUN_BOOKMARK_GOTO:
922                 flag.enabled(isSavedPosition(convert<unsigned int>(cmd.argument)));
923                 break;
924         case LFUN_CHANGES_TRACK:
925                 flag.enabled(true);
926                 flag.setOnOff(buffer_->params().tracking_changes);
927                 break;
928
929         case LFUN_CHANGES_OUTPUT: {
930                 OutputParams runparams;
931                 LaTeXFeatures features(*buffer_, buffer_->params(), runparams);
932                 flag.enabled(buffer_ && buffer_->params().tracking_changes
933                         && features.isAvailable("dvipost"));
934                 flag.setOnOff(buffer_->params().output_changes);
935                 break;
936         }
937
938         case LFUN_CHANGES_MERGE:
939         case LFUN_CHANGE_ACCEPT: // what about these two
940         case LFUN_CHANGE_REJECT: // what about these two
941         case LFUN_ALL_CHANGES_ACCEPT:
942         case LFUN_ALL_CHANGES_REJECT:
943                 flag.enabled(buffer_ && buffer_->params().tracking_changes);
944                 break;
945
946         case LFUN_BUFFER_TOGGLE_COMPRESSION: {
947                 flag.setOnOff(buffer_->params().compressed);
948                 break;
949         }
950
951         default:
952                 flag.enabled(false);
953         }
954
955         return flag;
956 }
957
958
959
960 bool BufferView::Pimpl::dispatch(FuncRequest const & cmd)
961 {
962         //lyxerr << BOOST_CURRENT_FUNCTION
963         //       << [ cmd = " << cmd << "]" << endl;
964
965         // Make sure that the cached BufferView is correct.
966         lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
967                 << " action[" << cmd.action << ']'
968                 << " arg[" << cmd.argument << ']'
969                 << " x[" << cmd.x << ']'
970                 << " y[" << cmd.y << ']'
971                 << " button[" << cmd.button() << ']'
972                 << endl;
973
974         LCursor & cur = cursor_;
975
976         switch (cmd.action) {
977
978         case LFUN_UNDO:
979                 if (available()) {
980                         cur.message(_("Undo"));
981                         cur.clearSelection();
982                         if (!textUndo(*bv_))
983                                 cur.message(_("No further undo information"));
984                         update();
985                         switchKeyMap();
986                 }
987                 break;
988
989         case LFUN_REDO:
990                 if (available()) {
991                         cur.message(_("Redo"));
992                         cur.clearSelection();
993                         if (!textRedo(*bv_))
994                                 cur.message(_("No further redo information"));
995                         update();
996                         switchKeyMap();
997                 }
998                 break;
999
1000         case LFUN_FILE_INSERT:
1001                 menuInsertLyXFile(cmd.argument);
1002                 break;
1003
1004         case LFUN_FILE_INSERT_ASCII_PARA:
1005                 insertAsciiFile(bv_, cmd.argument, true);
1006                 break;
1007
1008         case LFUN_FILE_INSERT_ASCII:
1009                 insertAsciiFile(bv_, cmd.argument, false);
1010                 break;
1011
1012         case LFUN_FONT_STATE:
1013                 cur.message(cur.currentState());
1014                 break;
1015
1016         case LFUN_BOOKMARK_SAVE:
1017                 savePosition(convert<unsigned int>(cmd.argument));
1018                 break;
1019
1020         case LFUN_BOOKMARK_GOTO:
1021                 restorePosition(convert<unsigned int>(cmd.argument));
1022                 break;
1023
1024         case LFUN_LABEL_GOTO: {
1025                 string label = cmd.argument;
1026                 if (label.empty()) {
1027                         InsetRef * inset =
1028                                 getInsetByCode<InsetRef>(cursor_,
1029                                                          InsetBase::REF_CODE);
1030                         if (inset) {
1031                                 label = inset->getContents();
1032                                 savePosition(0);
1033                         }
1034                 }
1035
1036                 if (!label.empty())
1037                         bv_->gotoLabel(label);
1038                 break;
1039         }
1040
1041         case LFUN_PARAGRAPH_GOTO: {
1042                 int const id = convert<int>(cmd.argument);
1043                 ParIterator par = buffer_->getParFromID(id);
1044                 if (par == buffer_->par_iterator_end()) {
1045                         lyxerr[Debug::INFO] << "No matching paragraph found! ["
1046                                             << id << ']' << endl;
1047                         break;
1048                 } else {
1049                         lyxerr[Debug::INFO] << "Paragraph " << par->id()
1050                                             << " found." << endl;
1051                 }
1052
1053                 // Set the cursor
1054                 bv_->setCursor(makeDocIterator(par, 0));
1055
1056                 update();
1057                 switchKeyMap();
1058                 break;
1059         }
1060
1061         case LFUN_OUTLINE_UP:
1062                 lyx::toc::outline(lyx::toc::Up, cursor_);
1063                 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
1064                 updateLabels(*buffer_);
1065                 break;
1066         case LFUN_OUTLINE_DOWN:
1067                 lyx::toc::outline(lyx::toc::Down, cursor_);
1068                 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
1069                 updateLabels(*buffer_);
1070                 break;
1071         case LFUN_OUTLINE_IN:
1072                 lyx::toc::outline(lyx::toc::In, cursor_);
1073                 updateLabels(*buffer_);
1074                 break;
1075         case LFUN_OUTLINE_OUT:
1076                 lyx::toc::outline(lyx::toc::Out, cursor_);
1077                 updateLabels(*buffer_);
1078                 break;
1079
1080         case LFUN_NOTE_NEXT:
1081                 bv_funcs::gotoInset(bv_, InsetBase::NOTE_CODE, false);
1082                 break;
1083
1084         case LFUN_REFERENCE_NEXT: {
1085                 vector<InsetBase_code> tmp;
1086                 tmp.push_back(InsetBase::LABEL_CODE);
1087                 tmp.push_back(InsetBase::REF_CODE);
1088                 bv_funcs::gotoInset(bv_, tmp, true);
1089                 break;
1090         }
1091
1092         case LFUN_CHANGES_TRACK:
1093                 trackChanges();
1094                 break;
1095
1096         case LFUN_CHANGES_OUTPUT: {
1097                 bool const state = buffer_->params().output_changes;
1098                 buffer_->params().output_changes = !state;
1099                 break;
1100         }
1101
1102         case LFUN_CHANGES_MERGE:
1103                 if (lyx::find::findNextChange(bv_))
1104                         owner_->getDialogs().show("changes");
1105                 break;
1106
1107         case LFUN_ALL_CHANGES_ACCEPT: {
1108                 cursor_.reset(buffer_->inset());
1109 #ifdef WITH_WARNINGS
1110 #warning FIXME changes
1111 #endif
1112                 while (lyx::find::findNextChange(bv_))
1113                         bv_->getLyXText()->acceptChange(cursor_);
1114                 update();
1115                 break;
1116         }
1117
1118         case LFUN_ALL_CHANGES_REJECT: {
1119                 cursor_.reset(buffer_->inset());
1120 #ifdef WITH_WARNINGS
1121 #warning FIXME changes
1122 #endif
1123                 while (lyx::find::findNextChange(bv_))
1124                         bv_->getLyXText()->rejectChange(cursor_);
1125                 break;
1126         }
1127
1128         case LFUN_WORD_FIND:
1129                 lyx::find::find(bv_, cmd);
1130                 break;
1131
1132         case LFUN_WORD_REPLACE:
1133                 lyx::find::replace(bv_, cmd);
1134                 break;
1135
1136         case LFUN_MARK_OFF:
1137                 cur.clearSelection();
1138                 cur.resetAnchor();
1139                 cur.message(N_("Mark off"));
1140                 break;
1141
1142         case LFUN_MARK_ON:
1143                 cur.clearSelection();
1144                 cur.mark() = true;
1145                 cur.resetAnchor();
1146                 cur.message(N_("Mark on"));
1147                 break;
1148
1149         case LFUN_MARK_TOGGLE:
1150                 cur.clearSelection();
1151                 if (cur.mark()) {
1152                         cur.mark() = false;
1153                         cur.message(N_("Mark removed"));
1154                 } else {
1155                         cur.mark() = true;
1156                         cur.message(N_("Mark set"));
1157                 }
1158                 cur.resetAnchor();
1159                 break;
1160
1161         case LFUN_SCREEN_RECENTER:
1162                 center();
1163                 break;
1164
1165         case LFUN_BIBTEX_DATABASE_ADD: {
1166                 LCursor tmpcur = cursor_;
1167                 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
1168                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1169                                                 InsetBase::BIBTEX_CODE);
1170                 if (inset) {
1171                         if (inset->addDatabase(cmd.argument))
1172                                 buffer_->updateBibfilesCache();
1173                 }
1174                 break;
1175         }
1176
1177         case LFUN_BIBTEX_DATABASE_DEL: {
1178                 LCursor tmpcur = cursor_;
1179                 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
1180                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1181                                                 InsetBase::BIBTEX_CODE);
1182                 if (inset) {
1183                         if (inset->delDatabase(cmd.argument))
1184                                 buffer_->updateBibfilesCache();
1185                 }
1186                 break;
1187         }
1188
1189         case LFUN_WORDS_COUNT: {
1190                 DocIterator from, to;
1191                 if (cur.selection()) {
1192                         from = cur.selectionBegin();
1193                         to = cur.selectionEnd();
1194                 } else {
1195                         from = doc_iterator_begin(buffer_->inset());
1196                         to = doc_iterator_end(buffer_->inset());
1197                 }
1198                 int const count = countWords(from, to);
1199                 string message;
1200                 if (count != 1) {
1201                         if (cur.selection())
1202                                 message = bformat(_("%1$d words in selection."),
1203                                           count);
1204                                 else
1205                                         message = bformat(_("%1$d words in document."),
1206                                                           count);
1207                 }
1208                 else {
1209                         if (cur.selection())
1210                                 message = _("One word in selection.");
1211                         else
1212                                 message = _("One word in document.");
1213                 }
1214
1215                 Alert::information(_("Count words"), message);
1216         }
1217                 break;
1218
1219         case LFUN_BUFFER_TOGGLE_COMPRESSION:
1220                 // turn compression on/off
1221                 buffer_->params().compressed = !buffer_->params().compressed;
1222                 break;
1223
1224         case LFUN_NEXT_INSET_TOGGLE: {
1225                 // this is the real function we want to invoke
1226                 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1227                 // if there is an inset at cursor, see whether it
1228                 // wants to toggle.
1229                 InsetBase * inset = cur.nextInset();
1230                 if (inset && inset->isActive()) {
1231                         LCursor tmpcur = cur;
1232                         tmpcur.pushLeft(*inset);
1233                         inset->dispatch(tmpcur, tmpcmd);
1234                         if (tmpcur.result().dispatched()) {
1235                                 cur.dispatched();
1236                         }
1237                 }
1238                 // if it did not work, try the underlying inset.
1239                 if (!cur.result().dispatched())
1240                         cur.dispatch(tmpcmd);
1241
1242                 if (cur.result().dispatched()) 
1243                         cur.clearSelection();
1244                 
1245                 break;
1246         }
1247
1248         default:
1249                 return false;
1250         }
1251
1252         return true;
1253 }
1254
1255
1256 void BufferView::Pimpl::updateMetrics(bool singlepar)
1257 {
1258         // Remove old position cache
1259         theCoords.clear();
1260         BufferView & bv = *bv_;
1261         LyXText * const text = bv.text();
1262         lyx::pit_type size = int(text->paragraphs().size());
1263
1264         if (anchor_ref_ > int(text->paragraphs().size() - 1)) {
1265                 anchor_ref_ = int(text->paragraphs().size() - 1);
1266                 offset_ref_ = 0;
1267         }
1268
1269         lyx::pit_type const pit = anchor_ref_;
1270         int pit1 = pit;
1271         int pit2 = pit;
1272         size_t const npit = text->paragraphs().size();
1273
1274         // Rebreak anchor paragraph. In Single Paragraph mode, rebreak only
1275         // the (main text, not inset!) paragraph containing the cursor.
1276         // (if this paragraph contains insets etc., rebreaking will
1277         // recursively descend)
1278         if (!singlepar || pit == cursor_.bottom().pit())
1279                 text->redoParagraph(pit);
1280         int y0 = text->getPar(pit).ascent() - offset_ref_;
1281
1282         // Redo paragraphs above anchor if necessary; again, in Single Par
1283         // mode, only if we encounter the (main text) one having the cursor.
1284         int y1 = y0;
1285         while (y1 > 0 && pit1 > 0) {
1286                 y1 -= text->getPar(pit1).ascent();
1287                 --pit1;
1288                 if (!singlepar || pit1 == cursor_.bottom().pit())
1289                         text->redoParagraph(pit1);
1290                 y1 -= text->getPar(pit1).descent();
1291         }
1292
1293
1294         // Take care of ascent of first line
1295         y1 -= text->getPar(pit1).ascent();
1296
1297         // Normalize anchor for next time
1298         anchor_ref_ = pit1;
1299         offset_ref_ = -y1;
1300
1301         // Grey at the beginning is ugly
1302         if (pit1 == 0 && y1 > 0) {
1303                 y0 -= y1;
1304                 y1 = 0;
1305                 anchor_ref_ = 0;
1306         }
1307
1308         // Redo paragraphs below the anchor if necessary. Single par mode:
1309         // only the one containing the cursor if encountered.
1310         int y2 = y0;
1311         while (y2 < bv.workHeight() && pit2 < int(npit) - 1) {
1312                 y2 += text->getPar(pit2).descent();
1313                 ++pit2;
1314                 if (!singlepar || pit2 == cursor_.bottom().pit())
1315                         text->redoParagraph(pit2);
1316                 y2 += text->getPar(pit2).ascent();
1317         }
1318
1319         // Take care of descent of last line
1320         y2 += text->getPar(pit2).descent();
1321
1322         // The coordinates of all these paragraphs are correct, cache them
1323         int y = y1;
1324         CoordCache::InnerParPosCache & parPos = theCoords.parPos()[text];
1325         for (lyx::pit_type pit = pit1; pit <= pit2; ++pit) {
1326                 Paragraph const & par = text->getPar(pit);
1327                 y += par.ascent();
1328                 parPos[pit] = Point(0, y);
1329                 if (singlepar && pit == cursor_.bottom().pit()) {
1330                         // In Single Paragraph mode, collect here the
1331                         // y1 and y2 of the (one) paragraph the cursor is in
1332                         y1 = y - par.ascent();
1333                         y2 = y + par.descent();
1334                 }
1335                 y += par.descent();
1336         }
1337
1338         if (singlepar) {
1339                 // collect cursor paragraph iter bounds
1340                 pit1 = cursor_.bottom().pit();
1341                 pit2 = cursor_.bottom().pit();
1342         }
1343
1344         lyxerr[Debug::DEBUG]
1345                 << BOOST_CURRENT_FUNCTION
1346                 << " y1: " << y1
1347                 << " y2: " << y2
1348                 << " pit1: " << pit1
1349                 << " pit2: " << pit2
1350                 << " npit: " << npit
1351                 << " singlepar: " << singlepar
1352                 << "size: " << size
1353                 << endl;
1354
1355         metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2, singlepar, size);
1356 }