]> git.lyx.org Git - lyx.git/blob - src/BufferView.cpp
Cosmetics.
[lyx.git] / src / BufferView.cpp
1 /**
2  * \file BufferView.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Alfredo Braunstein
7  * \author Lars Gullik Bjønnes
8  * \author John Levon
9  * \author André Pönitz
10  * \author Jürgen Vigna
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16
17 #include "BufferView.h"
18
19 #include "Buffer.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
23 #include "callback.h" // added for Dispatch functions
24 #include "CoordCache.h"
25 #include "CutAndPaste.h"
26 #include "debug.h"
27 #include "DispatchResult.h"
28 #include "ErrorList.h"
29 #include "factory.h"
30 #include "FloatList.h"
31 #include "FuncRequest.h"
32 #include "FuncStatus.h"
33 #include "gettext.h"
34 #include "Intl.h"
35 #include "InsetIterator.h"
36 #include "Language.h"
37 #include "LaTeXFeatures.h"
38 #include "LyX.h"
39 #include "lyxfind.h"
40 #include "LyXFunc.h"
41 #include "Layout.h"
42 #include "LyXRC.h"
43 #include "MetricsInfo.h"
44 #include "Paragraph.h"
45 #include "paragraph_funcs.h"
46 #include "ParagraphParameters.h"
47 #include "ParIterator.h"
48 #include "Session.h"
49 #include "TexRow.h"
50 #include "Text.h"
51 #include "TextClass.h"
52 #include "Undo.h"
53 #include "VSpace.h"
54 #include "WordLangTuple.h"
55
56 #include "insets/InsetBibtex.h"
57 #include "insets/InsetCommand.h" // ChangeRefs
58 #include "insets/InsetRef.h"
59 #include "insets/InsetText.h"
60
61 #include "frontends/alert.h"
62 #include "frontends/FileDialog.h"
63 #include "frontends/FontMetrics.h"
64 #include "frontends/Painter.h"
65 #include "frontends/Selection.h"
66
67 #include "graphics/Previews.h"
68
69 #include "support/convert.h"
70 #include "support/FileFilterList.h"
71 #include "support/filetools.h"
72 #include "support/Package.h"
73 #include "support/types.h"
74
75 #include <boost/bind.hpp>
76 #include <boost/current_function.hpp>
77
78 #include <functional>
79 #include <vector>
80
81 using std::distance;
82 using std::endl;
83 using std::istringstream;
84 using std::make_pair;
85 using std::min;
86 using std::max;
87 using std::mem_fun_ref;
88 using std::string;
89 using std::vector;
90
91
92 namespace lyx {
93
94 using support::addPath;
95 using support::bformat;
96 using support::FileFilterList;
97 using support::FileName;
98 using support::fileSearch;
99 using support::isDirWriteable;
100 using support::isFileReadable;
101 using support::makeDisplayPath;
102 using support::package;
103
104 namespace Alert = frontend::Alert;
105
106 namespace {
107
108 /// Return an inset of this class if it exists at the current cursor position
109 template <class T>
110 T * getInsetByCode(Cursor const & cur, Inset::Code code)
111 {
112         DocIterator it = cur;
113         Inset * inset = it.nextInset();
114         if (inset && inset->lyxCode() == code)
115                 return static_cast<T*>(inset);
116         return 0;
117 }
118
119
120 bool findInset(DocIterator & dit, vector<Inset_code> const & codes,
121         bool same_content);
122
123 bool findNextInset(DocIterator & dit, vector<Inset_code> const & codes,
124         string const & contents)
125 {
126         DocIterator tmpdit = dit;
127
128         while (tmpdit) {
129                 Inset const * inset = tmpdit.nextInset();
130                 if (inset
131                     && find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()
132                     && (contents.empty() ||
133                     static_cast<InsetCommand const *>(inset)->getContents() == contents)) {
134                         dit = tmpdit;
135                         return true;
136                 }
137                 tmpdit.forwardInset();
138         }
139
140         return false;
141 }
142
143
144 /// Looks for next inset with one of the the given code
145 bool findInset(DocIterator & dit, vector<Inset_code> const & codes,
146         bool same_content)
147 {
148         string contents;
149         DocIterator tmpdit = dit;
150         tmpdit.forwardInset();
151         if (!tmpdit)
152                 return false;
153
154         if (same_content) {
155                 Inset const * inset = tmpdit.nextInset();
156                 if (inset
157                     && find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()) {
158                         contents = static_cast<InsetCommand const *>(inset)->getContents();
159                 }
160         }
161
162         if (!findNextInset(tmpdit, codes, contents)) {
163                 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
164                         tmpdit  = doc_iterator_begin(tmpdit.bottom().inset());
165                         if (!findNextInset(tmpdit, codes, contents))
166                                 return false;
167                 } else
168                         return false;
169         }
170
171         dit = tmpdit;
172         return true;
173 }
174
175
176 /// Looks for next inset with the given code
177 void findInset(DocIterator & dit, Inset_code code, bool same_content)
178 {
179         findInset(dit, vector<Inset_code>(1, code), same_content);
180 }
181
182
183 /// Moves cursor to the next inset with one of the given codes.
184 void gotoInset(BufferView * bv, vector<Inset_code> const & codes,
185                bool same_content)
186 {
187         Cursor tmpcur = bv->cursor();
188         if (!findInset(tmpcur, codes, same_content)) {
189                 bv->cursor().message(_("No more insets"));
190                 return;
191         }
192
193         tmpcur.clearSelection();
194         bv->setCursor(tmpcur);
195 }
196
197
198 /// Moves cursor to the next inset with given code.
199 void gotoInset(BufferView * bv, Inset_code code, bool same_content)
200 {
201         gotoInset(bv, vector<Inset_code>(1, code), same_content);
202 }
203
204
205
206 /// the type of outline operation
207 enum OutlineOp {
208         OutlineUp, // Move this header with text down
209         OutlineDown,   // Move this header with text up
210         OutlineIn, // Make this header deeper
211         OutlineOut // Make this header shallower
212 };
213
214
215 void outline(OutlineOp mode, Cursor & cur)
216 {
217         Buffer & buf = cur.buffer();
218         pit_type & pit = cur.pit();
219         ParagraphList & pars = buf.text().paragraphs();
220         ParagraphList::iterator bgn = pars.begin();
221         // The first paragraph of the area to be copied:
222         ParagraphList::iterator start = boost::next(bgn, pit);
223         // The final paragraph of area to be copied:
224         ParagraphList::iterator finish = start;
225         ParagraphList::iterator end = pars.end();
226
227         TextClass::const_iterator lit =
228                 buf.params().getTextClass().begin();
229         TextClass::const_iterator const lend =
230                 buf.params().getTextClass().end();
231
232         int const thistoclevel = start->layout()->toclevel;
233         int toclevel;
234         switch (mode) {
235                 case OutlineUp: {
236                         // Move out (down) from this section header
237                         if (finish != end)
238                                 ++finish;
239                         // Seek the one (on same level) below
240                         for (; finish != end; ++finish) {
241                                 toclevel = finish->layout()->toclevel;
242                                 if (toclevel != Layout::NOT_IN_TOC
243                                     && toclevel <= thistoclevel) {
244                                         break;
245                                 }
246                         }
247                         ParagraphList::iterator dest = start;
248                         // Move out (up) from this header
249                         if (dest == bgn)
250                                 break;
251                         // Search previous same-level header above
252                         do {
253                                 --dest;
254                                 toclevel = dest->layout()->toclevel;
255                         } while(dest != bgn
256                                 && (toclevel == Layout::NOT_IN_TOC
257                                     || toclevel > thistoclevel));
258                         // Not found; do nothing
259                         if (toclevel == Layout::NOT_IN_TOC || toclevel > thistoclevel)
260                                 break;
261                         pit_type const newpit = std::distance(bgn, dest);
262                         pit_type const len = std::distance(start, finish);
263                         pit_type const deletepit = pit + len;
264                         recordUndo(cur, Undo::ATOMIC, newpit, deletepit - 1);
265                         pars.insert(dest, start, finish);
266                         start = boost::next(pars.begin(), deletepit);
267                         pit = newpit;
268                         pars.erase(start, finish);
269                         break;
270                 }
271                 case OutlineDown: {
272                         // Go down out of current header:
273                         if (finish != end)
274                                 ++finish;
275                         // Find next same-level header:
276                         for (; finish != end; ++finish) {
277                                 toclevel = finish->layout()->toclevel;
278                                 if (toclevel != Layout::NOT_IN_TOC && toclevel <= thistoclevel)
279                                         break;
280                         }
281                         ParagraphList::iterator dest = finish;
282                         // Go one down from *this* header:
283                         if (dest != end)
284                                 ++dest;
285                         else
286                                 break;
287                         // Go further down to find header to insert in front of:
288                         for (; dest != end; ++dest) {
289                                 toclevel = dest->layout()->toclevel;
290                                 if (toclevel != Layout::NOT_IN_TOC && toclevel <= thistoclevel)
291                                         break;
292                         }
293                         // One such was found:
294                         pit_type newpit = std::distance(bgn, dest);
295                         pit_type const len = std::distance(start, finish);
296                         recordUndo(cur, Undo::ATOMIC, pit, newpit - 1);
297                         pars.insert(dest, start, finish);
298                         start = boost::next(bgn, pit);
299                         pit = newpit - len;
300                         pars.erase(start, finish);
301                         break;
302                 }
303                 case OutlineIn:
304                         recordUndo(cur);
305                         for (; lit != lend; ++lit) {
306                                 if ((*lit)->toclevel == thistoclevel + 1 &&
307                                     start->layout()->labeltype == (*lit)->labeltype) {
308                                         start->layout((*lit));
309                                         break;
310                                 }
311                         }
312                         break;
313                 case OutlineOut:
314                         recordUndo(cur);
315                         for (; lit != lend; ++lit) {
316                                 if ((*lit)->toclevel == thistoclevel - 1 &&
317                                     start->layout()->labeltype == (*lit)->labeltype) {
318                                         start->layout((*lit));
319                                         break;
320                                 }
321                         }
322                         break;
323                 default:
324                         break;
325         }
326 }
327
328 } // anon namespace
329
330
331 /////////////////////////////////////////////////////////////////////
332 //
333 // BufferView
334 //
335 /////////////////////////////////////////////////////////////////////
336
337
338 BufferView::BufferView(Buffer & buf)
339         : width_(0), height_(0), buffer_(buf), wh_(0),
340           cursor_(*this),
341           multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
342           need_centering_(false), intl_(new Intl), last_inset_(0)
343 {
344         xsel_cache_.set = false;
345         intl_->initKeyMapper(lyxrc.use_kbmap);
346
347         cursor_.push(buffer_.inset());
348         cursor_.resetAnchor();
349         cursor_.setCurrentFont();
350
351         if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
352                 graphics::Previews::get().generateBufferPreviews(buffer_);
353 }
354
355
356 BufferView::~BufferView()
357 {
358         // current buffer is going to be switched-off, save cursor pos
359         // Ideally, the whole cursor stack should be saved, but session
360         // currently can only handle bottom (whole document) level pit and pos.
361         // That is to say, if a cursor is in a nested inset, it will be
362         // restore to the left of the top level inset.
363         LyX::ref().session().lastFilePos().save(
364                 support::FileName(buffer_.fileName()),
365                 boost::tie(cursor_.bottom().pit(), cursor_.bottom().pos()) );
366 }
367
368
369 Buffer & BufferView::buffer()
370 {
371         return buffer_;
372 }
373
374
375 Buffer const & BufferView::buffer() const
376 {
377         return buffer_;
378 }
379
380
381 bool BufferView::fitCursor()
382 {
383         if (cursorStatus(cursor_) == CUR_INSIDE) {
384                 frontend::FontMetrics const & fm =
385                         theFontMetrics(cursor_.getFont());
386                 int const asc = fm.maxAscent();
387                 int const des = fm.maxDescent();
388                 Point const p = getPos(cursor_, cursor_.boundary());
389                 if (p.y_ - asc >= 0 && p.y_ + des < height_)
390                         return false;
391         }
392         center();
393         return true;
394 }
395
396
397 bool BufferView::multiParSel()
398 {
399         if (!cursor_.selection())
400                 return false;
401         bool ret = multiparsel_cache_;
402         multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
403         // Either this, or previous selection spans paragraphs
404         return ret || multiparsel_cache_;
405 }
406
407
408 bool BufferView::update(Update::flags flags)
409 {
410         // last_inset_ points to the last visited inset. This pointer may become
411         // invalid because of keyboard editing. Since all such operations
412         // causes screen update(), I reset last_inset_ to avoid such a problem.
413         last_inset_ = 0;
414         // This is close to a hot-path.
415         LYXERR(Debug::DEBUG)
416                 << BOOST_CURRENT_FUNCTION
417                 << "[fitcursor = " << (flags & Update::FitCursor)
418                 << ", forceupdate = " << (flags & Update::Force)
419                 << ", singlepar = " << (flags & Update::SinglePar)
420                 << "]  buffer: " << &buffer_ << endl;
421
422         // Update macro store
423         if (!(cursor().inMathed() && cursor().inMacroMode()))
424                 buffer_.buildMacros();
425
426         // Now do the first drawing step if needed. This consists on updating
427         // the CoordCache in updateMetrics().
428         // The second drawing step is done in WorkArea::redraw() if needed.
429
430         // Case when no explicit update is requested.
431         if (!flags) {
432                 // no need to redraw anything.
433                 metrics_info_.update_strategy = NoScreenUpdate;
434                 return false;
435         }
436
437         if (flags == Update::Decoration) {
438                 metrics_info_.update_strategy = DecorationUpdate;
439                 return true;
440         }
441
442         if (flags == Update::FitCursor
443                 || flags == (Update::Decoration | Update::FitCursor)) {
444                 bool const fit_cursor = fitCursor();
445                 // tell the frontend to update the screen if needed.
446                 if (fit_cursor) {
447                         updateMetrics(false);
448                         return true;
449                 }
450                 if (flags & Update::Decoration) {
451                         metrics_info_.update_strategy = DecorationUpdate;
452                         return true;
453                 }
454                 // no screen update is needed.
455                 metrics_info_.update_strategy = NoScreenUpdate;
456                 return false;
457         }
458
459         bool full_metrics = flags & Update::Force;
460         if (flags & Update::MultiParSel)
461                 full_metrics |= multiParSel();
462
463         bool const single_par = !full_metrics;
464         updateMetrics(single_par);
465
466         if (flags & Update::FitCursor) {
467                 //FIXME: updateMetrics() does not update paragraph position
468                 // This is done at draw() time. So we need a redraw!
469                 buffer_.changed();
470                 if (fitCursor())
471                         updateMetrics(false);
472                 else
473                         // The screen has already been updated thanks to the
474                         // 'buffer_.changed()' call three line above. So no need
475                         // to redraw again.
476                         return false;
477         }
478
479         // tell the frontend to update the screen.
480         return true;
481 }
482
483
484 void BufferView::updateScrollbar()
485 {
486         Text & t = buffer_.text();
487         TextMetrics & tm = text_metrics_[&t];
488
489         int const parsize = int(t.paragraphs().size() - 1);
490         if (anchor_ref_ >  parsize)  {
491                 anchor_ref_ = parsize;
492                 offset_ref_ = 0;
493         }
494
495         LYXERR(Debug::GUI)
496                 << BOOST_CURRENT_FUNCTION
497                 << " Updating scrollbar: height: " << t.paragraphs().size()
498                 << " curr par: " << cursor_.bottom().pit()
499                 << " default height " << defaultRowHeight() << endl;
500
501         // It would be better to fix the scrollbar to understand
502         // values in [0..1] and divide everything by wh
503
504         // estimated average paragraph height:
505         if (wh_ == 0)
506                 wh_ = height_ / 4;
507
508         int h = tm.parMetrics(anchor_ref_).height();
509
510         // Normalize anchor/offset (MV):
511         while (offset_ref_ > h && anchor_ref_ < parsize) {
512                 anchor_ref_++;
513                 offset_ref_ -= h;
514                 h = tm.parMetrics(anchor_ref_).height();
515         }
516         // Look at paragraph heights on-screen
517         int sumh = 0;
518         int nh = 0;
519         for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
520                 if (sumh > height_)
521                         break;
522                 int const h2 = tm.parMetrics(pit).height();
523                 sumh += h2;
524                 nh++;
525         }
526
527         BOOST_ASSERT(nh);
528         int const hav = sumh / nh;
529         // More realistic average paragraph height
530         if (hav > wh_)
531                 wh_ = hav;
532
533         BOOST_ASSERT(h);
534         scrollbarParameters_.height = (parsize + 1) * wh_;
535         scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
536         scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
537 }
538
539
540 ScrollbarParameters const & BufferView::scrollbarParameters() const
541 {
542         return scrollbarParameters_;
543 }
544
545
546 void BufferView::scrollDocView(int value)
547 {
548         LYXERR(Debug::GUI) << BOOST_CURRENT_FUNCTION
549                            << "[ value = " << value << "]" << endl;
550
551         Text & t = buffer_.text();
552         TextMetrics & tm = text_metrics_[&t];
553
554         float const bar = value / float(wh_ * t.paragraphs().size());
555
556         anchor_ref_ = int(bar * t.paragraphs().size());
557         if (anchor_ref_ >  int(t.paragraphs().size()) - 1)
558                 anchor_ref_ = int(t.paragraphs().size()) - 1;
559
560         tm.redoParagraph(anchor_ref_);
561         int const h = tm.parMetrics(anchor_ref_).height();
562         offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
563         updateMetrics(false);
564         buffer_.changed();
565 }
566
567
568 void BufferView::setCursorFromScrollbar()
569 {
570         TextMetrics & tm = text_metrics_[&buffer_.text()];
571
572         int const height = 2 * defaultRowHeight();
573         int const first = height;
574         int const last = height_ - height;
575         Cursor & cur = cursor_;
576
577         switch (cursorStatus(cur)) {
578         case CUR_ABOVE:
579                 // We reset the cursor because cursorStatus() does not
580                 // work when the cursor is within mathed.
581                 cur.reset(buffer_.inset());
582                 tm.setCursorFromCoordinates(cur, 0, first);
583                 cur.clearSelection();
584                 break;
585         case CUR_BELOW:
586                 // We reset the cursor because cursorStatus() does not
587                 // work when the cursor is within mathed.
588                 cur.reset(buffer_.inset());
589                 tm.setCursorFromCoordinates(cur, 0, last);
590                 cur.clearSelection();
591                 break;
592         case CUR_INSIDE:
593                 int const y = getPos(cur, cur.boundary()).y_;
594                 int const newy = min(last, max(y, first));
595                 if (y != newy) {
596                         cur.reset(buffer_.inset());
597                         tm.setCursorFromCoordinates(cur, 0, newy);
598                 }
599         }
600 }
601
602
603 Change const BufferView::getCurrentChange() const
604 {
605         if (!cursor_.selection())
606                 return Change(Change::UNCHANGED);
607
608         DocIterator dit = cursor_.selectionBegin();
609         return dit.paragraph().lookupChange(dit.pos());
610 }
611
612
613 // this could be used elsewhere as well?
614 // FIXME: This does not work within mathed!
615 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
616 {
617         Point const p = getPos(dit, dit.boundary());
618         if (p.y_ < 0)
619                 return CUR_ABOVE;
620         if (p.y_ > workHeight())
621                 return CUR_BELOW;
622         return CUR_INSIDE;
623 }
624
625
626 void BufferView::saveBookmark(unsigned int idx)
627 {
628         // tenatively save bookmark, id and pos will be used to
629         // acturately locate a bookmark in a 'live' lyx session.
630         // pit and pos will be updated with bottom level pit/pos
631         // when lyx exits.
632         LyX::ref().session().bookmarks().save(
633                 FileName(buffer_.fileName()),
634                 cursor_.bottom().pit(),
635                 cursor_.bottom().pos(),
636                 cursor_.paragraph().id(),
637                 cursor_.pos(),
638                 idx
639         );
640         if (idx)
641                 // emit message signal.
642                 message(_("Save bookmark"));
643 }
644
645
646 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
647         int top_id, pos_type top_pos)
648 {
649         bool success = false;
650         DocIterator doc_it;
651
652         cursor_.clearSelection();
653
654         // if a valid par_id is given, try it first
655         // This is the case for a 'live' bookmark when unique paragraph ID
656         // is used to track bookmarks.
657         if (top_id > 0) {
658                 ParIterator par = buffer_.getParFromID(top_id);
659                 if (par != buffer_.par_iterator_end()) {
660                         doc_it = makeDocIterator(par, min(par->size(), top_pos));
661                         // Some slices of the iterator may not be
662                         // reachable (e.g. closed collapsable inset)
663                         // so the dociterator may need to be
664                         // shortened. Otherwise, setCursor may crash
665                         // lyx when the cursor can not be set to these
666                         // insets.
667                         size_t const n = doc_it.depth();
668                         for (size_t i = 0; i < n; ++i)
669                                 if (doc_it[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
670                                         doc_it.resize(i);
671                                         break;
672                                 }
673                         success = true;
674                 }
675         }
676
677         // if top_id == 0, or searching through top_id failed
678         // This is the case for a 'restored' bookmark when only bottom
679         // (document level) pit was saved. Because of this, bookmark
680         // restoration is inaccurate. If a bookmark was within an inset,
681         // it will be restored to the left of the outmost inset that contains
682         // the bookmark.
683         if (static_cast<size_t>(bottom_pit) < buffer_.paragraphs().size()) {
684                 doc_it = doc_iterator_begin(buffer_.inset());
685                 doc_it.pit() = bottom_pit;
686                 doc_it.pos() = min(bottom_pos, doc_it.paragraph().size());
687                 success = true;
688         }
689
690         if (success) {
691                 // Note: only bottom (document) level pit is set.
692                 setCursor(doc_it);
693                 // set the current font.
694                 cursor_.setCurrentFont();
695                 // center the screen on this new position.
696                 center();
697         }
698
699         return success;
700 }
701
702
703 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
704 {
705         if (lyxrc.rtl_support) {
706                 if (cursor_.real_current_font.isRightToLeft()) {
707                         if (intl_->keymap == Intl::PRIMARY)
708                                 intl_->keyMapSec();
709                 } else {
710                         if (intl_->keymap == Intl::SECONDARY)
711                                 intl_->keyMapPrim();
712                 }
713         }
714
715         intl_->getTransManager().translateAndInsert(c, t, cur);
716 }
717
718
719 int BufferView::workWidth() const
720 {
721         return width_;
722 }
723
724
725 void BufferView::updateOffsetRef()
726 {
727         // No need to update offset_ref_ in this case.
728         if (!need_centering_)
729                 return;
730
731         // We are not properly started yet, delay until resizing is
732         // done.
733         if (height_ == 0)
734                 return;
735
736         CursorSlice & bot = cursor_.bottom();
737         TextMetrics & tm = text_metrics_[bot.text()];
738         ParagraphMetrics const & pm = tm.parMetrics(bot.pit());
739         int y = coordOffset(cursor_, cursor_.boundary()).y_;
740         offset_ref_ = y + pm.ascent() - height_ / 2;
741
742         need_centering_ = false;
743 }
744
745
746 void BufferView::center()
747 {
748         anchor_ref_ = cursor_.bottom().pit();
749         need_centering_ = true;
750 }
751
752
753 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
754 {
755         FuncStatus flag;
756
757         Cursor & cur = cursor_;
758
759         switch (cmd.action) {
760
761         case LFUN_UNDO:
762                 flag.enabled(!buffer_.undostack().empty());
763                 break;
764         case LFUN_REDO:
765                 flag.enabled(!buffer_.redostack().empty());
766                 break;
767         case LFUN_FILE_INSERT:
768         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
769         case LFUN_FILE_INSERT_PLAINTEXT:
770         case LFUN_BOOKMARK_SAVE:
771                 // FIXME: Actually, these LFUNS should be moved to Text
772                 flag.enabled(cur.inTexted());
773                 break;
774         case LFUN_FONT_STATE:
775         case LFUN_LABEL_INSERT:
776         case LFUN_PARAGRAPH_GOTO:
777         // FIXME handle non-trivially
778         case LFUN_OUTLINE_UP:
779         case LFUN_OUTLINE_DOWN:
780         case LFUN_OUTLINE_IN:
781         case LFUN_OUTLINE_OUT:
782         case LFUN_NOTE_NEXT:
783         case LFUN_REFERENCE_NEXT:
784         case LFUN_WORD_FIND:
785         case LFUN_WORD_REPLACE:
786         case LFUN_MARK_OFF:
787         case LFUN_MARK_ON:
788         case LFUN_MARK_TOGGLE:
789         case LFUN_SCREEN_RECENTER:
790         case LFUN_BIBTEX_DATABASE_ADD:
791         case LFUN_BIBTEX_DATABASE_DEL:
792         case LFUN_WORDS_COUNT:
793         case LFUN_NEXT_INSET_TOGGLE:
794                 flag.enabled(true);
795                 break;
796
797         case LFUN_LABEL_GOTO: {
798                 flag.enabled(!cmd.argument().empty()
799                     || getInsetByCode<InsetRef>(cur, Inset::REF_CODE));
800                 break;
801         }
802
803         case LFUN_CHANGES_TRACK:
804                 flag.enabled(true);
805                 flag.setOnOff(buffer_.params().trackChanges);
806                 break;
807
808         case LFUN_CHANGES_OUTPUT:
809                 flag.enabled(true);
810                 flag.setOnOff(buffer_.params().outputChanges);
811                 break;
812
813         case LFUN_CHANGES_MERGE:
814         case LFUN_CHANGE_NEXT:
815         case LFUN_ALL_CHANGES_ACCEPT:
816         case LFUN_ALL_CHANGES_REJECT:
817                 // TODO: context-sensitive enabling of LFUNs
818                 // In principle, these command should only be enabled if there
819                 // is a change in the document. However, without proper
820                 // optimizations, this will inevitably result in poor performance.
821                 flag.enabled(true);
822                 break;
823
824         case LFUN_BUFFER_TOGGLE_COMPRESSION: {
825                 flag.setOnOff(buffer_.params().compressed);
826                 break;
827         }
828
829         case LFUN_SCREEN_UP:
830         case LFUN_SCREEN_DOWN:
831                 flag.enabled(true);
832                 break;
833
834         // FIXME: LFUN_SCREEN_DOWN_SELECT should be removed from
835         // everywhere else before this can enabled:
836         case LFUN_SCREEN_UP_SELECT:
837         case LFUN_SCREEN_DOWN_SELECT:
838                 flag.enabled(false);
839                 break;
840
841         default:
842                 flag.enabled(false);
843         }
844
845         return flag;
846 }
847
848
849 Update::flags BufferView::dispatch(FuncRequest const & cmd)
850 {
851         //lyxerr << BOOST_CURRENT_FUNCTION
852         //       << [ cmd = " << cmd << "]" << endl;
853
854         // Make sure that the cached BufferView is correct.
855         LYXERR(Debug::ACTION) << BOOST_CURRENT_FUNCTION
856                 << " action[" << cmd.action << ']'
857                 << " arg[" << to_utf8(cmd.argument()) << ']'
858                 << " x[" << cmd.x << ']'
859                 << " y[" << cmd.y << ']'
860                 << " button[" << cmd.button() << ']'
861                 << endl;
862
863         Cursor & cur = cursor_;
864         // Default Update flags.
865         Update::flags updateFlags = Update::Force | Update::FitCursor;
866
867         switch (cmd.action) {
868
869         case LFUN_UNDO:
870                 cur.message(_("Undo"));
871                 cur.clearSelection();
872                 if (!textUndo(*this)) {
873                         cur.message(_("No further undo information"));
874                         updateFlags = Update::None;
875                 }
876                 break;
877
878         case LFUN_REDO:
879                 cur.message(_("Redo"));
880                 cur.clearSelection();
881                 if (!textRedo(*this)) {
882                         cur.message(_("No further redo information"));
883                         updateFlags = Update::None;
884                 }
885                 break;
886
887         case LFUN_FILE_INSERT:
888                 // FIXME UNICODE
889                 menuInsertLyXFile(to_utf8(cmd.argument()));
890                 break;
891
892         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
893                 // FIXME UNICODE
894                 insertPlaintextFile(this, to_utf8(cmd.argument()), true);
895                 break;
896
897         case LFUN_FILE_INSERT_PLAINTEXT:
898                 // FIXME UNICODE
899                 insertPlaintextFile(this, to_utf8(cmd.argument()), false);
900                 break;
901
902         case LFUN_FONT_STATE:
903                 cur.message(cur.currentState());
904                 break;
905
906         case LFUN_BOOKMARK_SAVE:
907                 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
908                 break;
909
910         case LFUN_LABEL_GOTO: {
911                 docstring label = cmd.argument();
912                 if (label.empty()) {
913                         InsetRef * inset =
914                                 getInsetByCode<InsetRef>(cursor_,
915                                                          Inset::REF_CODE);
916                         if (inset) {
917                                 label = inset->getParam("reference");
918                                 // persistent=false: use temp_bookmark
919                                 saveBookmark(0);
920                         }
921                 }
922
923                 if (!label.empty())
924                         gotoLabel(label);
925                 break;
926         }
927
928         case LFUN_PARAGRAPH_GOTO: {
929                 int const id = convert<int>(to_utf8(cmd.argument()));
930                 int i = 0;
931                 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
932                         b = theBufferList().next(b)) {
933
934                         ParIterator par = b->getParFromID(id);
935                         if (par == b->par_iterator_end()) {
936                                 LYXERR(Debug::INFO)
937                                         << "No matching paragraph found! ["
938                                         << id << "]." << endl;
939                         } else {
940                                 LYXERR(Debug::INFO)
941                                         << "Paragraph " << par->id()
942                                         << " found in buffer `"
943                                         << b->fileName() << "'." << endl;
944
945                                 if (b == &buffer_) {
946                                         // Set the cursor
947                                         setCursor(makeDocIterator(par, 0));
948                                 } else {
949                                         // Switch to other buffer view and resend cmd
950                                         theLyXFunc().dispatch(FuncRequest(
951                                                 LFUN_BUFFER_SWITCH, b->fileName()));
952                                         theLyXFunc().dispatch(cmd);
953                                         updateFlags = Update::None;
954                                 }
955                                 break;
956                         }
957                         ++i;
958                 }
959                 break;
960         }
961
962         case LFUN_OUTLINE_UP:
963                 outline(OutlineUp, cursor_);
964                 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
965                 updateLabels(buffer_);
966                 break;
967         case LFUN_OUTLINE_DOWN:
968                 outline(OutlineDown, cursor_);
969                 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
970                 updateLabels(buffer_);
971                 break;
972         case LFUN_OUTLINE_IN:
973                 outline(OutlineIn, cursor_);
974                 updateLabels(buffer_);
975                 break;
976         case LFUN_OUTLINE_OUT:
977                 outline(OutlineOut, cursor_);
978                 updateLabels(buffer_);
979                 break;
980
981         case LFUN_NOTE_NEXT:
982                 gotoInset(this, Inset::NOTE_CODE, false);
983                 break;
984
985         case LFUN_REFERENCE_NEXT: {
986                 vector<Inset_code> tmp;
987                 tmp.push_back(Inset::LABEL_CODE);
988                 tmp.push_back(Inset::REF_CODE);
989                 gotoInset(this, tmp, true);
990                 break;
991         }
992
993         case LFUN_CHANGES_TRACK:
994                 buffer_.params().trackChanges = !buffer_.params().trackChanges;
995                 break;
996
997         case LFUN_CHANGES_OUTPUT:
998                 buffer_.params().outputChanges = !buffer_.params().outputChanges;
999                 if (buffer_.params().outputChanges) {
1000                         bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
1001                         bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1002                                           LaTeXFeatures::isAvailable("xcolor");
1003
1004                         if (!dvipost && !xcolorsoul) {
1005                                 Alert::warning(_("Changes not shown in LaTeX output"),
1006                                                _("Changes will not be highlighted in LaTeX output, "
1007                                                  "because neither dvipost nor xcolor/soul are installed.\n"
1008                                                  "Please install these packages or redefine "
1009                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1010                         } else if (!xcolorsoul) {
1011                                 Alert::warning(_("Changes not shown in LaTeX output"),
1012                                                _("Changes will not be highlighted in LaTeX output "
1013                                                  "when using pdflatex, because xcolor and soul are not installed.\n"
1014                                                  "Please install both packages or redefine "
1015                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1016                         }
1017                 }
1018                 break;
1019
1020         case LFUN_CHANGE_NEXT:
1021                 findNextChange(this);
1022                 break;
1023
1024         case LFUN_CHANGES_MERGE:
1025                 if (findNextChange(this))
1026                         showDialog("changes");
1027                 break;
1028
1029         case LFUN_ALL_CHANGES_ACCEPT:
1030                 // select complete document
1031                 cursor_.reset(buffer_.inset());
1032                 cursor_.selHandle(true);
1033                 buffer_.text().cursorBottom(cursor_);
1034                 // accept everything in a single step to support atomic undo
1035                 buffer_.text().acceptOrRejectChanges(cursor_, Text::ACCEPT);
1036                 break;
1037
1038         case LFUN_ALL_CHANGES_REJECT:
1039                 // select complete document
1040                 cursor_.reset(buffer_.inset());
1041                 cursor_.selHandle(true);
1042                 buffer_.text().cursorBottom(cursor_);
1043                 // reject everything in a single step to support atomic undo
1044                 // Note: reject does not work recursively; the user may have to repeat the operation
1045                 buffer_.text().acceptOrRejectChanges(cursor_, Text::REJECT);
1046                 break;
1047
1048         case LFUN_WORD_FIND:
1049                 find(this, cmd);
1050                 break;
1051
1052         case LFUN_WORD_REPLACE: {
1053                 bool has_deleted = false;
1054                 if (cur.selection()) {
1055                         DocIterator beg = cur.selectionBegin();
1056                         DocIterator end = cur.selectionEnd();
1057                         if (beg.pit() == end.pit()) {
1058                                 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1059                                         if (cur.paragraph().isDeleted(p))
1060                                                 has_deleted = true;
1061                                 }
1062                         }
1063                 }
1064                 replace(this, cmd, has_deleted);
1065                 break;
1066         }
1067
1068         case LFUN_MARK_OFF:
1069                 cur.clearSelection();
1070                 cur.resetAnchor();
1071                 cur.message(from_utf8(N_("Mark off")));
1072                 break;
1073
1074         case LFUN_MARK_ON:
1075                 cur.clearSelection();
1076                 cur.mark() = true;
1077                 cur.resetAnchor();
1078                 cur.message(from_utf8(N_("Mark on")));
1079                 break;
1080
1081         case LFUN_MARK_TOGGLE:
1082                 cur.clearSelection();
1083                 if (cur.mark()) {
1084                         cur.mark() = false;
1085                         cur.message(from_utf8(N_("Mark removed")));
1086                 } else {
1087                         cur.mark() = true;
1088                         cur.message(from_utf8(N_("Mark set")));
1089                 }
1090                 cur.resetAnchor();
1091                 break;
1092
1093         case LFUN_SCREEN_RECENTER:
1094                 center();
1095                 break;
1096
1097         case LFUN_BIBTEX_DATABASE_ADD: {
1098                 Cursor tmpcur = cursor_;
1099                 findInset(tmpcur, Inset::BIBTEX_CODE, false);
1100                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1101                                                 Inset::BIBTEX_CODE);
1102                 if (inset) {
1103                         if (inset->addDatabase(to_utf8(cmd.argument())))
1104                                 buffer_.updateBibfilesCache();
1105                 }
1106                 break;
1107         }
1108
1109         case LFUN_BIBTEX_DATABASE_DEL: {
1110                 Cursor tmpcur = cursor_;
1111                 findInset(tmpcur, Inset::BIBTEX_CODE, false);
1112                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1113                                                 Inset::BIBTEX_CODE);
1114                 if (inset) {
1115                         if (inset->delDatabase(to_utf8(cmd.argument())))
1116                                 buffer_.updateBibfilesCache();
1117                 }
1118                 break;
1119         }
1120
1121         case LFUN_WORDS_COUNT: {
1122                 DocIterator from, to;
1123                 if (cur.selection()) {
1124                         from = cur.selectionBegin();
1125                         to = cur.selectionEnd();
1126                 } else {
1127                         from = doc_iterator_begin(buffer_.inset());
1128                         to = doc_iterator_end(buffer_.inset());
1129                 }
1130                 int const count = countWords(from, to);
1131                 docstring message;
1132                 if (count != 1) {
1133                         if (cur.selection())
1134                                 message = bformat(_("%1$d words in selection."),
1135                                           count);
1136                                 else
1137                                         message = bformat(_("%1$d words in document."),
1138                                                           count);
1139                 }
1140                 else {
1141                         if (cur.selection())
1142                                 message = _("One word in selection.");
1143                         else
1144                                 message = _("One word in document.");
1145                 }
1146
1147                 Alert::information(_("Count words"), message);
1148         }
1149                 break;
1150
1151         case LFUN_BUFFER_TOGGLE_COMPRESSION:
1152                 // turn compression on/off
1153                 buffer_.params().compressed = !buffer_.params().compressed;
1154                 break;
1155
1156         case LFUN_NEXT_INSET_TOGGLE: {
1157                 // this is the real function we want to invoke
1158                 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1159                 // if there is an inset at cursor, see whether it
1160                 // wants to toggle.
1161                 Inset * inset = cur.nextInset();
1162                 if (inset) {
1163                         if (inset->isActive()) {
1164                                 Cursor tmpcur = cur;
1165                                 tmpcur.pushLeft(*inset);
1166                                 inset->dispatch(tmpcur, tmpcmd);
1167                                 if (tmpcur.result().dispatched()) {
1168                                         cur.dispatched();
1169                                 }
1170                         } else if (inset->editable() == Inset::IS_EDITABLE) {
1171                                 inset->edit(cur, true);
1172                         }
1173                 }
1174                 // if it did not work, try the underlying inset.
1175                 if (!cur.result().dispatched())
1176                         cur.dispatch(tmpcmd);
1177
1178                 if (cur.result().dispatched())
1179                         cur.clearSelection();
1180
1181                 break;
1182         }
1183
1184         case LFUN_SCREEN_UP:
1185         case LFUN_SCREEN_DOWN: {
1186                 Point p = getPos(cur, cur.boundary());
1187                 if (p.y_ < 0 || p.y_ > height_) {
1188                         // The cursor is off-screen so recenter before proceeding.
1189                         center();
1190                         updateMetrics(false);
1191                         //FIXME: updateMetrics() does not update paragraph position
1192                         // This is done at draw() time. So we need a redraw!
1193                         buffer_.changed();
1194                         p = getPos(cur, cur.boundary());
1195                 }
1196                 scroll(cmd.action == LFUN_SCREEN_UP? - height_ : height_);
1197                 cur.reset(buffer_.inset());
1198                 text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1199                 //FIXME: what to do with cur.x_target()?
1200                 finishUndo();
1201                 // The metrics are already up to date. see scroll()
1202                 updateFlags = Update::None;
1203                 break;
1204         }
1205
1206         case LFUN_SCREEN_UP_SELECT:
1207         case LFUN_SCREEN_DOWN_SELECT: {
1208                 cur.selHandle(true);
1209                 size_t initial_depth = cur.depth();
1210                 Point const p = getPos(cur, cur.boundary());
1211                 scroll(cmd.action == LFUN_SCREEN_UP_SELECT? - height_ : height_);
1212                 // FIXME: We need to verify if the cursor stayed within an inset...
1213                 //cur.reset(buffer_.inset());
1214                 text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1215                 finishUndo();
1216                 while (cur.depth() > initial_depth) {
1217                         cur.forwardInset();
1218                 }
1219                 // FIXME: we need to do a redraw again because of the selection
1220                 buffer_.changed();
1221                 updateFlags = Update::Force | Update::FitCursor;
1222                 break;
1223         }
1224
1225         default:
1226                 updateFlags = Update::None;
1227         }
1228
1229         return updateFlags;
1230 }
1231
1232
1233 docstring const BufferView::requestSelection()
1234 {
1235         Cursor & cur = cursor_;
1236
1237         if (!cur.selection()) {
1238                 xsel_cache_.set = false;
1239                 return docstring();
1240         }
1241
1242         if (!xsel_cache_.set ||
1243             cur.top() != xsel_cache_.cursor ||
1244             cur.anchor_.top() != xsel_cache_.anchor)
1245         {
1246                 xsel_cache_.cursor = cur.top();
1247                 xsel_cache_.anchor = cur.anchor_.top();
1248                 xsel_cache_.set = cur.selection();
1249                 return cur.selectionAsString(false);
1250         }
1251         return docstring();
1252 }
1253
1254
1255 void BufferView::clearSelection()
1256 {
1257         cursor_.clearSelection();
1258         // Clear the selection buffer. Otherwise a subsequent
1259         // middle-mouse-button paste would use the selection buffer,
1260         // not the more current external selection.
1261         cap::clearSelection();
1262         xsel_cache_.set = false;
1263         // The buffer did not really change, but this causes the
1264         // redraw we need because we cleared the selection above.
1265         buffer_.changed();
1266 }
1267
1268
1269 void BufferView::resize(int width, int height)
1270 {
1271         // Update from work area
1272         width_ = width;
1273         height_ = height;
1274
1275         updateMetrics(false);
1276 }
1277
1278
1279 Inset const * BufferView::getCoveringInset(Text const & text, int x, int y)
1280 {
1281         TextMetrics & tm = text_metrics_[&text];
1282         Inset * inset = tm.checkInsetHit(x, y);
1283         if (!inset)
1284                 return 0;
1285
1286         if (!inset->descendable())
1287                 // No need to go further down if the inset is not
1288                 // descendable.
1289                 return inset;
1290
1291         size_t cell_number = inset->nargs();
1292         // Check all the inner cell.
1293         for (size_t i = 0; i != cell_number; ++i) {
1294                 Text const * inner_text = inset->getText(i);
1295                 if (inner_text) {
1296                         // Try deeper.
1297                         Inset const * inset_deeper =
1298                                 getCoveringInset(*inner_text, x, y);
1299                         if (inset_deeper)
1300                                 return inset_deeper;
1301                 }
1302         }
1303
1304         return inset;
1305 }
1306
1307
1308 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1309 {
1310         //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1311
1312         // This is only called for mouse related events including
1313         // LFUN_FILE_OPEN generated by drag-and-drop.
1314         FuncRequest cmd = cmd0;
1315
1316         Cursor cur(*this);
1317         cur.push(buffer_.inset());
1318         cur.selection() = cursor_.selection();
1319
1320         // Either the inset under the cursor or the
1321         // surrounding Text will handle this event.
1322
1323         // make sure we stay within the screen...
1324         cmd.y = min(max(cmd.y, -1), height_);
1325
1326         if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1327
1328                 // Get inset under mouse, if there is one.
1329                 Inset const * covering_inset =
1330                         getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1331                 if (covering_inset == last_inset_)
1332                         // Same inset, no need to do anything...
1333                         return false;
1334
1335                 bool need_redraw = false;
1336                 // const_cast because of setMouseHover().
1337                 Inset * inset = const_cast<Inset *>(covering_inset);
1338                 if (last_inset_)
1339                         // Remove the hint on the last hovered inset (if any).
1340                         need_redraw |= last_inset_->setMouseHover(false);
1341                 if (inset)
1342                         // Highlighted the newly hovered inset (if any).
1343                         need_redraw |= inset->setMouseHover(true);
1344                 last_inset_ = inset;
1345                 if (!need_redraw)
1346                         return false;
1347
1348                 // if last metrics update was in singlepar mode, WorkArea::redraw() will
1349                 // not expose the button for redraw. We adjust here the metrics dimension
1350                 // to enable a full redraw in any case as this is not costly.
1351                 TextMetrics & tm = text_metrics_[&buffer_.text()];
1352                 std::pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
1353                 std::pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
1354                 int y1 = firstpm.second->position() - firstpm.second->ascent();
1355                 int y2 = lastpm.second->position() + lastpm.second->descent();
1356                 metrics_info_ = ViewMetricsInfo(firstpm.first, lastpm.first, y1, y2,
1357                         FullScreenUpdate, buffer_.text().paragraphs().size());
1358                 // Reinitialize anchor to first pit.
1359                 anchor_ref_ = firstpm.first;
1360                 offset_ref_ = -y1;
1361                 LYXERR(Debug::PAINTING)
1362                         << "Mouse hover detected at: (" << cmd.x << ", " << cmd.y << ")"
1363                         << "\nTriggering redraw: y1: " << y1 << " y2: " << y2
1364                         << " pit1: " << firstpm.first << " pit2: " << lastpm.first << endl;
1365
1366                 // This event (moving without mouse click) is not passed further.
1367                 // This should be changed if it is further utilized.
1368                 return true;
1369         }
1370
1371         // Build temporary cursor.
1372         Inset * inset = text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1373
1374         // Put anchor at the same position.
1375         cur.resetAnchor();
1376
1377         // Try to dispatch to an non-editable inset near this position
1378         // via the temp cursor. If the inset wishes to change the real
1379         // cursor it has to do so explicitly by using
1380         //  cur.bv().cursor() = cur;  (or similar)
1381         if (inset) {
1382                 inset->dispatch(cur, cmd);
1383         }
1384
1385         // Now dispatch to the temporary cursor. If the real cursor should
1386         // be modified, the inset's dispatch has to do so explicitly.
1387         if (!cur.result().dispatched())
1388                 cur.dispatch(cmd);
1389
1390         //Do we have a selection?
1391         theSelection().haveSelection(cursor().selection());
1392
1393         // Redraw if requested and necessary.
1394         if (cur.result().dispatched() && cur.result().update())
1395                 return update(cur.result().update());
1396
1397         return false;
1398 }
1399
1400
1401 void BufferView::scroll(int y)
1402 {
1403         if (y > 0)
1404                 scrollDown(y);
1405         else if (y < 0)
1406                 scrollUp(-y);
1407 }
1408
1409
1410 void BufferView::scrollDown(int offset)
1411 {
1412         Text * text = &buffer_.text();
1413         TextMetrics & tm = text_metrics_[text];
1414         int ymax = height_ + offset;
1415         while (true) {
1416                 std::pair<pit_type, ParagraphMetrics const *> last = tm.last();
1417                 int bottom_pos = last.second->position() + last.second->descent();
1418                 if (last.first + 1 == int(text->paragraphs().size())) {
1419                         if (bottom_pos <= height_)
1420                                 return;
1421                         offset = min(offset, bottom_pos - height_);
1422                         break;
1423                 }
1424                 if (bottom_pos > ymax)
1425                         break;
1426                 tm.newParMetricsDown();
1427         }
1428         offset_ref_ += offset;
1429         updateMetrics(false);
1430         buffer_.changed();
1431 }
1432
1433
1434 void BufferView::scrollUp(int offset)
1435 {
1436         Text * text = &buffer_.text();
1437         TextMetrics & tm = text_metrics_[text];
1438         int ymin = - offset;
1439         while (true) {
1440                 std::pair<pit_type, ParagraphMetrics const *> first = tm.first();
1441                 int top_pos = first.second->position() - first.second->ascent();
1442                 if (first.first == 0) {
1443                         if (top_pos >= 0)
1444                                 return;
1445                         offset = min(offset, - top_pos);
1446                         break;
1447                 }
1448                 if (top_pos < ymin)
1449                         break;
1450                 tm.newParMetricsUp();
1451         }
1452         offset_ref_ -= offset;
1453         updateMetrics(false);
1454         buffer_.changed();
1455 }
1456
1457
1458 void BufferView::setCursorFromRow(int row)
1459 {
1460         int tmpid = -1;
1461         int tmppos = -1;
1462
1463         buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1464
1465         cursor_.reset(buffer_.inset());
1466         if (tmpid == -1)
1467                 buffer_.text().setCursor(cursor_, 0, 0);
1468         else
1469                 buffer_.text().setCursor(cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1470 }
1471
1472
1473 void BufferView::gotoLabel(docstring const & label)
1474 {
1475         for (InsetIterator it = inset_iterator_begin(buffer_.inset()); it; ++it) {
1476                 vector<docstring> labels;
1477                 it->getLabelList(buffer_, labels);
1478                 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1479                         setCursor(it);
1480                         update();
1481                         return;
1482                 }
1483         }
1484 }
1485
1486
1487 TextMetrics const & BufferView::textMetrics(Text const * t) const
1488 {
1489         return const_cast<BufferView *>(this)->textMetrics(t);
1490 }
1491
1492
1493 TextMetrics & BufferView::textMetrics(Text const * t)
1494 {
1495         TextMetricsCache::iterator tmc_it  = text_metrics_.find(t);
1496         if (tmc_it == text_metrics_.end()) {
1497                 tmc_it = text_metrics_.insert(
1498                         make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1499         }
1500         return tmc_it->second;
1501 }
1502
1503
1504 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1505                 pit_type pit) const
1506 {
1507         return textMetrics(t).parMetrics(pit);
1508 }
1509
1510
1511 int BufferView::workHeight() const
1512 {
1513         return height_;
1514 }
1515
1516
1517 void BufferView::setCursor(DocIterator const & dit)
1518 {
1519         size_t const n = dit.depth();
1520         for (size_t i = 0; i < n; ++i)
1521                 dit[i].inset().edit(cursor_, true);
1522
1523         cursor_.setCursor(dit);
1524         cursor_.selection() = false;
1525 }
1526
1527
1528 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1529 {
1530         // Would be wrong to delete anything if we have a selection.
1531         if (cur.selection())
1532                 return false;
1533
1534         bool need_anchor_change = false;
1535         bool changed = cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1536                 need_anchor_change);
1537
1538         if (need_anchor_change)
1539                 cur.resetAnchor();
1540
1541         if (!changed)
1542                 return false;
1543
1544         updateLabels(buffer_);
1545
1546         updateMetrics(false);
1547         buffer_.changed();
1548         return true;
1549 }
1550
1551
1552 bool BufferView::mouseSetCursor(Cursor & cur)
1553 {
1554         BOOST_ASSERT(&cur.bv() == this);
1555
1556         // this event will clear selection so we save selection for
1557         // persistent selection
1558         cap::saveSelection(cursor());
1559
1560         // Has the cursor just left the inset?
1561         bool badcursor = false;
1562         bool leftinset = (&cursor_.inset() != &cur.inset());
1563         if (leftinset)
1564                 badcursor = notifyCursorLeaves(cursor_, cur);
1565
1566         // do the dEPM magic if needed
1567         // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1568         // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1569         // the leftinset bool would not be necessary (badcursor instead).
1570         bool update = leftinset;
1571         if (!badcursor && cursor_.inTexted())
1572                 update |= checkDepm(cur, cursor_);
1573
1574         // if the cursor was in an empty script inset and the new
1575         // position is in the nucleus of the inset, notifyCursorLeaves
1576         // will kill the script inset itself. So we check all the
1577         // elements of the cursor to make sure that they are correct.
1578         // For an example, see bug 2933:
1579         // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1580         // The code below could maybe be moved to a DocIterator method.
1581         //lyxerr << "cur before " << cur <<std::endl;
1582         DocIterator dit(cur.inset());
1583         dit.push_back(cur.bottom());
1584         size_t i = 1;
1585         while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1586                 dit.push_back(cur[i]);
1587                 ++i;
1588         }
1589         //lyxerr << "5 cur after" << dit <<std::endl;
1590
1591         cursor_.setCursor(dit);
1592         cursor_.boundary(cur.boundary());
1593         cursor_.clearSelection();
1594         finishUndo();
1595         return update;
1596 }
1597
1598
1599 void BufferView::putSelectionAt(DocIterator const & cur,
1600                                 int length, bool backwards)
1601 {
1602         cursor_.clearSelection();
1603
1604         setCursor(cur);
1605
1606         if (length) {
1607                 if (backwards) {
1608                         cursor_.pos() += length;
1609                         cursor_.setSelection(cursor_, -length);
1610                 } else
1611                         cursor_.setSelection(cursor_, length);
1612         }
1613 }
1614
1615
1616 Cursor & BufferView::cursor()
1617 {
1618         return cursor_;
1619 }
1620
1621
1622 Cursor const & BufferView::cursor() const
1623 {
1624         return cursor_;
1625 }
1626
1627
1628 pit_type BufferView::anchor_ref() const
1629 {
1630         return anchor_ref_;
1631 }
1632
1633
1634 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1635 {
1636         return metrics_info_;
1637 }
1638
1639
1640 bool BufferView::singleParUpdate()
1641 {
1642         Text & buftext = buffer_.text();
1643         pit_type const bottom_pit = cursor_.bottom().pit();
1644         TextMetrics & tm = textMetrics(&buftext);
1645         int old_height = tm.parMetrics(bottom_pit).height();
1646
1647         // In Single Paragraph mode, rebreak only
1648         // the (main text, not inset!) paragraph containing the cursor.
1649         // (if this paragraph contains insets etc., rebreaking will
1650         // recursively descend)
1651         tm.redoParagraph(bottom_pit);
1652         ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);                
1653         if (pm.height() != old_height)
1654                 // Paragraph height has changed so we cannot proceed to
1655                 // the singlePar optimisation.
1656                 return false;
1657
1658         int y1 = pm.position() - pm.ascent();
1659         int y2 = pm.position() + pm.descent();
1660         metrics_info_ = ViewMetricsInfo(bottom_pit, bottom_pit, y1, y2,
1661                 SingleParUpdate, buftext.paragraphs().size());
1662         LYXERR(Debug::PAINTING)
1663                 << BOOST_CURRENT_FUNCTION
1664                 << "\ny1: " << y1
1665                 << " y2: " << y2
1666                 << " pit: " << bottom_pit
1667                 << " singlepar: 1"
1668                 << endl;
1669         return true;
1670 }
1671
1672
1673 void BufferView::updateMetrics(bool singlepar)
1674 {
1675         if (singlepar && singleParUpdate())
1676                 // No need to update the full screen metrics.
1677                 return;
1678
1679         Text & buftext = buffer_.text();
1680         pit_type const npit = int(buftext.paragraphs().size());
1681
1682         if (anchor_ref_ > int(npit - 1)) {
1683                 anchor_ref_ = int(npit - 1);
1684                 offset_ref_ = 0;
1685         }
1686
1687         // Clear out the position cache in case of full screen redraw,
1688         coord_cache_.clear();
1689
1690         // Clear out paragraph metrics to avoid having invalid metrics
1691         // in the cache from paragraphs not relayouted below
1692         // The complete text metrics will be redone.
1693         text_metrics_.clear();
1694
1695         TextMetrics & tm = textMetrics(&buftext);
1696
1697         pit_type const pit = anchor_ref_;
1698         int pit1 = pit;
1699         int pit2 = pit;
1700
1701         // Rebreak anchor paragraph.
1702         tm.redoParagraph(pit);
1703
1704         // Take care of anchor offset if case a recentering is needed.
1705         updateOffsetRef();
1706
1707         int y0 = tm.parMetrics(pit).ascent() - offset_ref_;
1708
1709         // Redo paragraphs above anchor if necessary.
1710         int y1 = y0;
1711         while (y1 > 0 && pit1 > 0) {
1712                 y1 -= tm.parMetrics(pit1).ascent();
1713                 --pit1;
1714                 tm.redoParagraph(pit1);
1715                 y1 -= tm.parMetrics(pit1).descent();
1716         }
1717
1718         // Take care of ascent of first line
1719         y1 -= tm.parMetrics(pit1).ascent();
1720
1721         // Normalize anchor for next time
1722         anchor_ref_ = pit1;
1723         offset_ref_ = -y1;
1724
1725         // Grey at the beginning is ugly
1726         if (pit1 == 0 && y1 > 0) {
1727                 y0 -= y1;
1728                 y1 = 0;
1729                 anchor_ref_ = 0;
1730         }
1731
1732         // Redo paragraphs below the anchor if necessary.
1733         int y2 = y0;
1734         while (y2 < height_ && pit2 < int(npit) - 1) {
1735                 y2 += tm.parMetrics(pit2).descent();
1736                 ++pit2;
1737                 tm.redoParagraph(pit2);
1738                 y2 += tm.parMetrics(pit2).ascent();
1739         }
1740
1741         // Take care of descent of last line
1742         y2 += tm.parMetrics(pit2).descent();
1743
1744         LYXERR(Debug::PAINTING)
1745                 << BOOST_CURRENT_FUNCTION
1746                 << "\n y1: " << y1
1747                 << " y2: " << y2
1748                 << " pit1: " << pit1
1749                 << " pit2: " << pit2
1750                 << " npit: " << npit
1751                 << " singlepar: 0"
1752                 << endl;
1753
1754         metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2,
1755                 FullScreenUpdate, npit);
1756
1757         if (lyxerr.debugging(Debug::WORKAREA)) {
1758                 LYXERR(Debug::WORKAREA) << "BufferView::updateMetrics" << endl;
1759                 coord_cache_.dump();
1760         }
1761 }
1762
1763
1764 void BufferView::menuInsertLyXFile(string const & filenm)
1765 {
1766         BOOST_ASSERT(cursor_.inTexted());
1767         string filename = filenm;
1768
1769         if (filename.empty()) {
1770                 // Launch a file browser
1771                 // FIXME UNICODE
1772                 string initpath = lyxrc.document_path;
1773                 string const trypath = buffer_.filePath();
1774                 // If directory is writeable, use this as default.
1775                 if (isDirWriteable(FileName(trypath)))
1776                         initpath = trypath;
1777
1778                 // FIXME UNICODE
1779                 FileDialog fileDlg(_("Select LyX document to insert"),
1780                         LFUN_FILE_INSERT,
1781                         make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1782                         make_pair(_("Examples|#E#e"),
1783                                     from_utf8(addPath(package().system_support().absFilename(),
1784                                     "examples"))));
1785
1786                 FileDialog::Result result =
1787                         fileDlg.open(from_utf8(initpath),
1788                                      FileFilterList(_("LyX Documents (*.lyx)")),
1789                                      docstring());
1790
1791                 if (result.first == FileDialog::Later)
1792                         return;
1793
1794                 // FIXME UNICODE
1795                 filename = to_utf8(result.second);
1796
1797                 // check selected filename
1798                 if (filename.empty()) {
1799                         // emit message signal.
1800                         message(_("Canceled."));
1801                         return;
1802                 }
1803         }
1804
1805         // Get absolute path of file and add ".lyx"
1806         // to the filename if necessary
1807         filename = fileSearch(string(), filename, "lyx").absFilename();
1808
1809         docstring const disp_fn = makeDisplayPath(filename);
1810         // emit message signal.
1811         message(bformat(_("Inserting document %1$s..."), disp_fn));
1812
1813         docstring res;
1814         Buffer buf("", false);
1815         if (lyx::loadLyXFile(&buf, FileName(filename))) {
1816                 ErrorList & el = buffer_.errorList("Parse");
1817                 // Copy the inserted document error list into the current buffer one.
1818                 el = buf.errorList("Parse");
1819                 recordUndo(cursor_);
1820                 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1821                                              buf.params().getTextClassPtr(), el);
1822                 res = _("Document %1$s inserted.");
1823         } else
1824                 res = _("Could not insert document %1$s");
1825
1826         // emit message signal.
1827         message(bformat(res, disp_fn));
1828         buffer_.errors("Parse");
1829         updateMetrics(false);
1830 }
1831
1832
1833 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
1834 {
1835         int x = 0;
1836         int y = 0;
1837         int lastw = 0;
1838
1839         // Addup contribution of nested insets, from inside to outside,
1840         // keeping the outer paragraph for a special handling below
1841         for (size_t i = dit.depth() - 1; i >= 1; --i) {
1842                 CursorSlice const & sl = dit[i];
1843                 int xx = 0;
1844                 int yy = 0;
1845                 
1846                 // get relative position inside sl.inset()
1847                 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
1848                 
1849                 // Make relative position inside of the edited inset relative to sl.inset()
1850                 x += xx;
1851                 y += yy;
1852                 
1853                 // In case of an RTL inset, the edited inset will be positioned to the left
1854                 // of xx:yy
1855                 if (sl.text()) {
1856                         bool boundary_i = boundary && i + 1 == dit.depth();
1857                         bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
1858                         if (rtl)
1859                                 x -= lastw;
1860                 }
1861
1862                 // remember width for the case that sl.inset() is positioned in an RTL inset
1863                 if (i && dit[i - 1].text()) {
1864                         // If this Inset is inside a Text Inset, retrieve the Dimension
1865                         // from the containing text instead of using Inset::dimension() which
1866                         // might not be implemented.
1867                         // FIXME (Abdel 23/09/2007): this is a bit messy because of the
1868                         // elimination of Inset::dim_ cache. This coordOffset() method needs
1869                         // to be rewritten in light of the new design.
1870                         Dimension const & dim = parMetrics(dit[i - 1].text(),
1871                                 dit[i - 1].pit()).insetDimension(&sl.inset());
1872                         lastw = dim.wid;
1873                 } else {
1874                         Dimension const dim = sl.inset().dimension(*this);
1875                         lastw = dim.wid;
1876                 }
1877                 
1878                 //lyxerr << "Cursor::getPos, i: "
1879                 // << i << " x: " << xx << " y: " << y << endl;
1880         }
1881
1882         // Add contribution of initial rows of outermost paragraph
1883         CursorSlice const & sl = dit[0];
1884         TextMetrics const & tm = textMetrics(sl.text());
1885         ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
1886         BOOST_ASSERT(!pm.rows().empty());
1887         y -= pm.rows()[0].ascent();
1888 #if 1
1889         // FIXME: document this mess
1890         size_t rend;
1891         if (sl.pos() > 0 && dit.depth() == 1) {
1892                 int pos = sl.pos();
1893                 if (pos && boundary)
1894                         --pos;
1895 //              lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << std::endl;
1896                 rend = pm.pos2row(pos);
1897         } else
1898                 rend = pm.pos2row(sl.pos());
1899 #else
1900         size_t rend = pm.pos2row(sl.pos());
1901 #endif
1902         for (size_t rit = 0; rit != rend; ++rit)
1903                 y += pm.rows()[rit].height();
1904         y += pm.rows()[rend].ascent();
1905         
1906         TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
1907         
1908         // Make relative position from the nested inset now bufferview absolute.
1909         int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
1910         x += xx;
1911         
1912         // In the RTL case place the nested inset at the left of the cursor in 
1913         // the outer paragraph
1914         bool boundary_1 = boundary && 1 == dit.depth();
1915         bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
1916         if (rtl)
1917                 x -= lastw;
1918         
1919         return Point(x, y);
1920 }
1921
1922
1923 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
1924 {
1925         CursorSlice const & bot = dit.bottom();
1926         TextMetrics const & tm = textMetrics(bot.text());
1927         if (!tm.has(bot.pit()))
1928                 return Point(-1, -1);
1929
1930         Point p = coordOffset(dit, boundary); // offset from outer paragraph
1931         p.y_ += tm.parMetrics(bot.pit()).position();
1932         return p;
1933 }
1934
1935
1936 void BufferView::draw(frontend::Painter & pain)
1937 {
1938         PainterInfo pi(this, pain);
1939         // Should the whole screen, including insets, be refreshed?
1940         // FIXME: We should also distinguish DecorationUpdate to avoid text
1941         // drawing if possible. This is not possible to do easily right now
1942         // because of the single backing pixmap.
1943         pi.full_repaint = metrics_info_.update_strategy != SingleParUpdate;
1944
1945         if (pi.full_repaint)
1946                 // Clear background (if not delegated to rows)
1947                 pain.fillRectangle(0, metrics_info_.y1, width_,
1948                         metrics_info_.y2 - metrics_info_.y1,
1949                         buffer_.inset().backgroundColor());
1950
1951         LYXERR(Debug::PAINTING) << "\t\t*** START DRAWING ***" << endl;
1952         Text & text = buffer_.text();
1953         TextMetrics const & tm = text_metrics_[&text];
1954         int y = metrics_info_.y1 + tm.parMetrics(metrics_info_.p1).ascent();
1955         if (!pi.full_repaint)
1956                 tm.drawParagraph(pi, metrics_info_.p1, 0, y);
1957         else
1958                 tm.draw(pi, 0, y);
1959         LYXERR(Debug::PAINTING) << "\n\t\t*** END DRAWING  ***" << endl;
1960
1961         // and grey out above (should not happen later)
1962 //      lyxerr << "par ascent: " << text.getPar(metrics_info_.p1).ascent() << endl;
1963         if (metrics_info_.y1 > 0
1964                 && metrics_info_.update_strategy == FullScreenUpdate)
1965                 pain.fillRectangle(0, 0, width_, metrics_info_.y1, Color::bottomarea);
1966
1967         // and possibly grey out below
1968 //      lyxerr << "par descent: " << text.getPar(metrics_info_.p1).ascent() << endl;
1969         if (metrics_info_.y2 < height_
1970                 && metrics_info_.update_strategy == FullScreenUpdate)
1971                 pain.fillRectangle(0, metrics_info_.y2, width_,
1972                         height_ - metrics_info_.y2, Color::bottomarea);
1973 }
1974
1975 } // namespace lyx