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