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