]> git.lyx.org Git - lyx.git/blob - src/BufferView.cpp
Fix bug 4733: Auto popup of math toolbar hides the math editor
[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 "BranchList.h"
20 #include "Buffer.h"
21 #include "buffer_funcs.h"
22 #include "BufferList.h"
23 #include "BufferParams.h"
24 #include "CoordCache.h"
25 #include "Cursor.h"
26 #include "CutAndPaste.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 "Intl.h"
34 #include "InsetIterator.h"
35 #include "Language.h"
36 #include "LaTeXFeatures.h"
37 #include "LyX.h"
38 #include "lyxfind.h"
39 #include "LyXFunc.h"
40 #include "Layout.h"
41 #include "LyXRC.h"
42 #include "MetricsInfo.h"
43 #include "Paragraph.h"
44 #include "paragraph_funcs.h"
45 #include "ParagraphParameters.h"
46 #include "ParIterator.h"
47 #include "Session.h"
48 #include "Text.h"
49 #include "TextClass.h"
50 #include "TextMetrics.h"
51 #include "TexRow.h"
52 #include "TocBackend.h"
53 #include "VSpace.h"
54 #include "WordLangTuple.h"
55
56 #include "insets/InsetBibtex.h"
57 #include "insets/InsetCommand.h" // ChangeRefs
58 #include "insets/InsetExternal.h"
59 #include "insets/InsetGraphics.h"
60 #include "insets/InsetRef.h"
61 #include "insets/InsetText.h"
62 #include "insets/InsetNote.h"
63
64 #include "frontends/alert.h"
65 #include "frontends/Application.h"
66 #include "frontends/Delegates.h"
67 #include "frontends/FontMetrics.h"
68 #include "frontends/Painter.h"
69 #include "frontends/Selection.h"
70
71 #include "graphics/Previews.h"
72
73 #include "support/convert.h"
74 #include "support/debug.h"
75 #include "support/ExceptionMessage.h"
76 #include "support/filetools.h"
77 #include "support/gettext.h"
78 #include "support/lstrings.h"
79 #include "support/Package.h"
80 #include "support/types.h"
81
82 #include <cerrno>
83 #include <fstream>
84 #include <functional>
85 #include <iterator>
86 #include <vector>
87
88 using namespace std;
89 using namespace lyx::support;
90
91 namespace lyx {
92
93 namespace Alert = frontend::Alert;
94
95 namespace {
96
97 /// Return an inset of this class if it exists at the current cursor position
98 template <class T>
99 T * getInsetByCode(Cursor const & cur, InsetCode code)
100 {
101         DocIterator it = cur;
102         Inset * inset = it.nextInset();
103         if (inset && inset->lyxCode() == code)
104                 return static_cast<T*>(inset);
105         return 0;
106 }
107
108
109 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
110         bool same_content);
111
112 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
113         docstring const & contents)
114 {
115         DocIterator tmpdit = dit;
116
117         while (tmpdit) {
118                 Inset const * inset = tmpdit.nextInset();
119                 if (inset
120                     && std::find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()
121                     && (contents.empty() ||
122                     static_cast<InsetCommand const *>(inset)->getFirstNonOptParam() == contents)) {
123                         dit = tmpdit;
124                         return true;
125                 }
126                 tmpdit.forwardInset();
127         }
128
129         return false;
130 }
131
132
133 /// Looks for next inset with one of the given codes.
134 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
135         bool same_content)
136 {
137         docstring contents;
138         DocIterator tmpdit = dit;
139         tmpdit.forwardInset();
140         if (!tmpdit)
141                 return false;
142
143         if (same_content) {
144                 Inset const * inset = tmpdit.nextInset();
145                 if (inset
146                     && std::find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()) {
147                         contents = static_cast<InsetCommand const *>(inset)->getFirstNonOptParam();
148                 }
149         }
150
151         if (!findNextInset(tmpdit, codes, contents)) {
152                 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
153                         Inset * inset = &tmpdit.bottom().inset();
154                         tmpdit = doc_iterator_begin(&inset->buffer(), inset);
155                         if (!findNextInset(tmpdit, codes, contents))
156                                 return false;
157                 } else {
158                         return false;
159                 }
160         }
161
162         dit = tmpdit;
163         return true;
164 }
165
166
167 /// Looks for next inset with the given code
168 void findInset(DocIterator & dit, InsetCode code, bool same_content)
169 {
170         findInset(dit, vector<InsetCode>(1, code), same_content);
171 }
172
173
174 /// Moves cursor to the next inset with one of the given codes.
175 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
176                bool same_content)
177 {
178         Cursor tmpcur = bv->cursor();
179         if (!findInset(tmpcur, codes, same_content)) {
180                 bv->cursor().message(_("No more insets"));
181                 return;
182         }
183
184         tmpcur.clearSelection();
185         bv->setCursor(tmpcur);
186         bv->showCursor();
187 }
188
189
190 /// Moves cursor to the next inset with given code.
191 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
192 {
193         gotoInset(bv, vector<InsetCode>(1, code), same_content);
194 }
195
196
197 /// A map from a Text to the associated text metrics
198 typedef map<Text const *, TextMetrics> TextMetricsCache;
199
200 enum ScreenUpdateStrategy {
201         NoScreenUpdate,
202         SingleParUpdate,
203         FullScreenUpdate,
204         DecorationUpdate
205 };
206
207 } // anon namespace
208
209
210 /////////////////////////////////////////////////////////////////////
211 //
212 // BufferView
213 //
214 /////////////////////////////////////////////////////////////////////
215
216 struct BufferView::Private
217 {
218         Private(BufferView & bv): wh_(0), cursor_(bv),
219                 anchor_pit_(0), anchor_ypos_(0),
220                 inlineCompletionUniqueChars_(0),
221                 last_inset_(0), bookmark_edit_position_(0), gui_(0)
222         {}
223
224         ///
225         ScrollbarParameters scrollbarParameters_;
226         ///
227         ScreenUpdateStrategy update_strategy_;
228         ///
229         CoordCache coord_cache_;
230
231         /// Estimated average par height for scrollbar.
232         int wh_;
233         /// this is used to handle XSelection events in the right manner.
234         struct {
235                 CursorSlice cursor;
236                 CursorSlice anchor;
237                 bool set;
238         } xsel_cache_;
239         ///
240         Cursor cursor_;
241         ///
242         pit_type anchor_pit_;
243         ///
244         int anchor_ypos_;
245         ///
246         vector<int> par_height_;
247
248         ///
249         DocIterator inlineCompletionPos_;
250         ///
251         docstring inlineCompletion_;
252         ///
253         size_t inlineCompletionUniqueChars_;
254
255         /// keyboard mapping object.
256         Intl intl_;
257
258         /// last visited inset.
259         /** kept to send setMouseHover(false).
260           * Not owned, so don't delete.
261           */
262         Inset * last_inset_;
263
264         // cache for id of the paragraph which was edited the last time
265         int bookmark_edit_position_;
266
267         mutable TextMetricsCache text_metrics_;
268
269         /// Whom to notify.
270         /** Not owned, so don't delete.
271           */
272         frontend::GuiBufferViewDelegate * gui_;
273
274         /// Cache for Find Next
275         FuncRequest search_request_cache_;
276 };
277
278
279 BufferView::BufferView(Buffer & buf)
280         : width_(0), height_(0), full_screen_(false), buffer_(buf),
281       d(new Private(*this))
282 {
283         d->xsel_cache_.set = false;
284         d->intl_.initKeyMapper(lyxrc.use_kbmap);
285
286         d->cursor_.setBuffer(&buf);
287         d->cursor_.push(buffer_.inset());
288         d->cursor_.resetAnchor();
289         d->cursor_.setCurrentFont();
290
291         if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
292                 thePreviews().generateBufferPreviews(buffer_);
293 }
294
295
296 BufferView::~BufferView()
297 {
298         // current buffer is going to be switched-off, save cursor pos
299         // Ideally, the whole cursor stack should be saved, but session
300         // currently can only handle bottom (whole document) level pit and pos.
301         // That is to say, if a cursor is in a nested inset, it will be
302         // restore to the left of the top level inset.
303         LastFilePosSection::FilePos fp;
304         fp.pit = d->cursor_.bottom().pit();
305         fp.pos = d->cursor_.bottom().pos();
306         theSession().lastFilePos().save(buffer_.fileName(), fp);
307
308         delete d;
309 }
310
311
312 int BufferView::rightMargin() const
313 {
314         // The additional test for the case the outliner is opened.
315         if (!full_screen_ ||
316                 !lyxrc.full_screen_limit ||
317                 width_ < lyxrc.full_screen_width + 20)
318                         return 10;
319
320         return (width_ - lyxrc.full_screen_width) / 2;
321 }
322
323
324 int BufferView::leftMargin() const
325 {
326         return rightMargin();
327 }
328
329
330 bool BufferView::isTopScreen() const
331 {
332         return d->scrollbarParameters_.position == d->scrollbarParameters_.min;
333 }
334
335
336 bool BufferView::isBottomScreen() const
337 {
338         return d->scrollbarParameters_.position == d->scrollbarParameters_.max;
339 }
340
341
342 Intl & BufferView::getIntl()
343 {
344         return d->intl_;
345 }
346
347
348 Intl const & BufferView::getIntl() const
349 {
350         return d->intl_;
351 }
352
353
354 CoordCache & BufferView::coordCache()
355 {
356         return d->coord_cache_;
357 }
358
359
360 CoordCache const & BufferView::coordCache() const
361 {
362         return d->coord_cache_;
363 }
364
365
366 Buffer & BufferView::buffer()
367 {
368         return buffer_;
369 }
370
371
372 Buffer const & BufferView::buffer() const
373 {
374         return buffer_;
375 }
376
377
378 bool BufferView::fitCursor()
379 {
380         if (cursorStatus(d->cursor_) == CUR_INSIDE) {
381                 frontend::FontMetrics const & fm =
382                         theFontMetrics(d->cursor_.getFont().fontInfo());
383                 int const asc = fm.maxAscent();
384                 int const des = fm.maxDescent();
385                 Point const p = getPos(d->cursor_, d->cursor_.boundary());
386                 if (p.y_ - asc >= 0 && p.y_ + des < height_)
387                         return false;
388         }
389         return true;
390 }
391
392
393 void BufferView::processUpdateFlags(Update::flags flags)
394 {
395         // last_inset_ points to the last visited inset. This pointer may become
396         // invalid because of keyboard editing. Since all such operations
397         // causes screen update(), I reset last_inset_ to avoid such a problem.
398         d->last_inset_ = 0;
399         // This is close to a hot-path.
400         LYXERR(Debug::DEBUG, "BufferView::processUpdateFlags()"
401                 << "[fitcursor = " << (flags & Update::FitCursor)
402                 << ", forceupdate = " << (flags & Update::Force)
403                 << ", singlepar = " << (flags & Update::SinglePar)
404                 << "]  buffer: " << &buffer_);
405
406         buffer_.updateMacros();
407
408         // Now do the first drawing step if needed. This consists on updating
409         // the CoordCache in updateMetrics().
410         // The second drawing step is done in WorkArea::redraw() if needed.
411
412         // Case when no explicit update is requested.
413         if (!flags) {
414                 // no need to redraw anything.
415                 d->update_strategy_ = NoScreenUpdate;
416                 return;
417         }
418
419         if (flags == Update::Decoration) {
420                 d->update_strategy_ = DecorationUpdate;
421                 buffer_.changed();
422                 return;
423         }
424
425         if (flags == Update::FitCursor
426                 || flags == (Update::Decoration | Update::FitCursor)) {
427                 // tell the frontend to update the screen if needed.
428                 if (fitCursor()) {
429                         showCursor();
430                         return;
431                 }
432                 if (flags & Update::Decoration) {
433                         d->update_strategy_ = DecorationUpdate;
434                         buffer_.changed();
435                         return;
436                 }
437                 // no screen update is needed.
438                 d->update_strategy_ = NoScreenUpdate;
439                 return;
440         }
441
442         bool const full_metrics = flags & Update::Force || !singleParUpdate();
443
444         if (full_metrics)
445                 // We have to update the full screen metrics.
446                 updateMetrics();
447
448         if (!(flags & Update::FitCursor)) {
449                 // Nothing to do anymore. Trigger a redraw and return
450                 buffer_.changed();
451                 return;
452         }
453
454         // updateMetrics() does not update paragraph position
455         // This is done at draw() time. So we need a redraw!
456         buffer_.changed();
457
458         if (fitCursor()) {
459                 // The cursor is off screen so ensure it is visible.
460                 // refresh it:
461                 showCursor();
462         }
463 }
464
465
466 void BufferView::updateScrollbar()
467 {
468         if (height_ == 0 && width_ == 0)
469                 return;
470
471         // We prefer fixed size line scrolling.
472         d->scrollbarParameters_.single_step = defaultRowHeight();
473         // We prefer full screen page scrolling.
474         d->scrollbarParameters_.page_step = height_;
475
476         Text & t = buffer_.text();
477         TextMetrics & tm = d->text_metrics_[&t];                
478
479         LYXERR(Debug::GUI, " Updating scrollbar: height: "
480                 << t.paragraphs().size()
481                 << " curr par: " << d->cursor_.bottom().pit()
482                 << " default height " << defaultRowHeight());
483
484         size_t const parsize = t.paragraphs().size();
485         if (d->par_height_.size() != parsize) {
486                 d->par_height_.clear();
487                 // FIXME: We assume a default paragraph height of 2 rows. This
488                 // should probably be pondered with the screen width.
489                 d->par_height_.resize(parsize, defaultRowHeight() * 2);
490         }
491
492         // Look at paragraph heights on-screen
493         pair<pit_type, ParagraphMetrics const *> first = tm.first();
494         pair<pit_type, ParagraphMetrics const *> last = tm.last();
495         for (pit_type pit = first.first; pit <= last.first; ++pit) {
496                 d->par_height_[pit] = tm.parMetrics(pit).height();
497                 LYXERR(Debug::SCROLLING, "storing height for pit " << pit << " : "
498                         << d->par_height_[pit]);
499         }
500
501         int top_pos = first.second->position() - first.second->ascent();
502         int bottom_pos = last.second->position() + last.second->descent();
503         bool first_visible = first.first == 0 && top_pos >= 0;
504         bool last_visible = last.first + 1 == int(parsize) && bottom_pos <= height_;
505         if (first_visible && last_visible) {
506                 d->scrollbarParameters_.min = 0;
507                 d->scrollbarParameters_.max = 0;
508                 return;
509         }
510
511         d->scrollbarParameters_.min = top_pos;
512         for (size_t i = 0; i != size_t(first.first); ++i)
513                 d->scrollbarParameters_.min -= d->par_height_[i];
514         d->scrollbarParameters_.max = bottom_pos;
515         for (size_t i = last.first + 1; i != parsize; ++i)
516                 d->scrollbarParameters_.max += d->par_height_[i];
517
518         d->scrollbarParameters_.position = 0;
519         // The reference is the top position so we remove one page.
520         d->scrollbarParameters_.max -= d->scrollbarParameters_.page_step;
521 }
522
523
524 ScrollbarParameters const & BufferView::scrollbarParameters() const
525 {
526         return d->scrollbarParameters_;
527 }
528
529
530 docstring BufferView::toolTip(int x, int y) const
531 {
532         // Get inset under mouse, if there is one.
533         Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
534         if (!covering_inset)
535                 // No inset, no tooltip...
536                 return docstring();
537         return covering_inset->toolTip(*this, x, y);
538 }
539
540
541 docstring BufferView::contextMenu(int x, int y) const
542 {
543         //If there is a selection, return the containing inset menu
544         if (d->cursor_.selection())
545                 return d->cursor_.inset().contextMenu(*this, x, y);
546
547         // Get inset under mouse, if there is one.
548         Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
549         if (covering_inset)
550                 return covering_inset->contextMenu(*this, x, y);
551
552         return buffer_.inset().contextMenu(*this, x, y);
553 }
554
555
556 void BufferView::scrollDocView(int value)
557 {
558         int const offset = value - d->scrollbarParameters_.position;
559
560         // No scrolling at all? No need to redraw anything
561         if (offset == 0)
562                 return;
563
564         // If the offset is less than 2 screen height, prefer to scroll instead.
565         if (abs(offset) <= 2 * height_) {
566                 d->anchor_ypos_ -= offset;
567                 updateMetrics();
568                 buffer_.changed();
569                 return;
570         }
571
572         // cut off at the top
573         if (value <= d->scrollbarParameters_.min) {
574                 DocIterator dit = doc_iterator_begin(&buffer_);
575                 showCursor(dit);
576                 LYXERR(Debug::SCROLLING, "scroll to top");
577                 return;
578         }
579
580         // cut off at the bottom
581         if (value >= d->scrollbarParameters_.max) {
582                 DocIterator dit = doc_iterator_end(&buffer_);
583                 dit.backwardPos();
584                 showCursor(dit);
585                 LYXERR(Debug::SCROLLING, "scroll to bottom");
586                 return;
587         }
588
589         // find paragraph at target position
590         int par_pos = d->scrollbarParameters_.min;
591         pit_type i = 0;
592         for (; i != int(d->par_height_.size()); ++i) {
593                 par_pos += d->par_height_[i];
594                 if (par_pos >= value)
595                         break;
596         }
597
598         if (par_pos < value) {
599                 // It seems we didn't find the correct pit so stay on the safe side and
600                 // scroll to bottom.
601                 LYXERR0("scrolling position not found!");
602                 scrollDocView(d->scrollbarParameters_.max);
603                 return;
604         }
605
606         DocIterator dit = doc_iterator_begin(&buffer_);
607         dit.pit() = i;
608         LYXERR(Debug::SCROLLING, "value = " << value << " -> scroll to pit " << i);
609         showCursor(dit);
610 }
611
612
613 // FIXME: this method is not working well.
614 void BufferView::setCursorFromScrollbar()
615 {
616         TextMetrics & tm = d->text_metrics_[&buffer_.text()];
617
618         int const height = 2 * defaultRowHeight();
619         int const first = height;
620         int const last = height_ - height;
621         int newy = 0;
622         Cursor const & oldcur = d->cursor_;
623
624         switch (cursorStatus(oldcur)) {
625         case CUR_ABOVE:
626                 newy = first;
627                 break;
628         case CUR_BELOW:
629                 newy = last;
630                 break;
631         case CUR_INSIDE:
632                 int const y = getPos(oldcur, oldcur.boundary()).y_;
633                 newy = min(last, max(y, first));
634                 if (y == newy) 
635                         return;
636         }
637         // We reset the cursor because cursorStatus() does not
638         // work when the cursor is within mathed.
639         Cursor cur(*this);
640         cur.reset(buffer_.inset());
641         tm.setCursorFromCoordinates(cur, 0, newy);
642
643         // update the bufferview cursor and notify insets
644         // FIXME: Care about the d->cursor_ flags to redraw if needed
645         Cursor old = d->cursor_;
646         mouseSetCursor(cur);
647         bool badcursor = notifyCursorLeavesOrEnters(old, d->cursor_);
648         if (badcursor)
649                 d->cursor_.fixIfBroken();
650 }
651
652
653 Change const BufferView::getCurrentChange() const
654 {
655         if (!d->cursor_.selection())
656                 return Change(Change::UNCHANGED);
657
658         DocIterator dit = d->cursor_.selectionBegin();
659         return dit.paragraph().lookupChange(dit.pos());
660 }
661
662
663 // this could be used elsewhere as well?
664 // FIXME: This does not work within mathed!
665 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
666 {
667         Point const p = getPos(dit, dit.boundary());
668         if (p.y_ < 0)
669                 return CUR_ABOVE;
670         if (p.y_ > workHeight())
671                 return CUR_BELOW;
672         return CUR_INSIDE;
673 }
674
675
676 void BufferView::bookmarkEditPosition()
677 {
678         // Don't eat cpu time for each keystroke
679         if (d->cursor_.paragraph().id() == d->bookmark_edit_position_)
680                 return;
681         saveBookmark(0);
682         d->bookmark_edit_position_ = d->cursor_.paragraph().id();
683 }
684
685
686 void BufferView::saveBookmark(unsigned int idx)
687 {
688         // tentatively save bookmark, id and pos will be used to
689         // acturately locate a bookmark in a 'live' lyx session.
690         // pit and pos will be updated with bottom level pit/pos
691         // when lyx exits.
692         theSession().bookmarks().save(
693                 buffer_.fileName(),
694                 d->cursor_.bottom().pit(),
695                 d->cursor_.bottom().pos(),
696                 d->cursor_.paragraph().id(),
697                 d->cursor_.pos(),
698                 idx
699         );
700         if (idx)
701                 // emit message signal.
702                 message(_("Save bookmark"));
703 }
704
705
706 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
707         int top_id, pos_type top_pos)
708 {
709         bool success = false;
710         DocIterator dit;
711
712         d->cursor_.clearSelection();
713
714         // if a valid par_id is given, try it first
715         // This is the case for a 'live' bookmark when unique paragraph ID
716         // is used to track bookmarks.
717         if (top_id > 0) {
718                 dit = buffer_.getParFromID(top_id);
719                 if (!dit.atEnd()) {
720                         dit.pos() = min(dit.paragraph().size(), top_pos);
721                         // Some slices of the iterator may not be
722                         // reachable (e.g. closed collapsable inset)
723                         // so the dociterator may need to be
724                         // shortened. Otherwise, setCursor may crash
725                         // lyx when the cursor can not be set to these
726                         // insets.
727                         size_t const n = dit.depth();
728                         for (size_t i = 0; i < n; ++i)
729                                 if (dit[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
730                                         dit.resize(i);
731                                         break;
732                                 }
733                         success = true;
734                 }
735         }
736
737         // if top_id == 0, or searching through top_id failed
738         // This is the case for a 'restored' bookmark when only bottom
739         // (document level) pit was saved. Because of this, bookmark
740         // restoration is inaccurate. If a bookmark was within an inset,
741         // it will be restored to the left of the outmost inset that contains
742         // the bookmark.
743         if (bottom_pit < int(buffer_.paragraphs().size())) {
744                 dit = doc_iterator_begin(&buffer_);
745                                 
746                 dit.pit() = bottom_pit;
747                 dit.pos() = min(bottom_pos, dit.paragraph().size());
748                 success = true;
749         }
750
751         if (success) {
752                 // Note: only bottom (document) level pit is set.
753                 setCursor(dit);
754                 // set the current font.
755                 d->cursor_.setCurrentFont();
756                 // To center the screen on this new position we need the
757                 // paragraph position which is computed at draw() time.
758                 // So we need a redraw!
759                 buffer_.changed();
760                 if (fitCursor())
761                         showCursor();
762         }
763
764         return success;
765 }
766
767
768 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
769 {
770         if (lyxrc.rtl_support) {
771                 if (d->cursor_.real_current_font.isRightToLeft()) {
772                         if (d->intl_.keymap == Intl::PRIMARY)
773                                 d->intl_.keyMapSec();
774                 } else {
775                         if (d->intl_.keymap == Intl::SECONDARY)
776                                 d->intl_.keyMapPrim();
777                 }
778         }
779
780         d->intl_.getTransManager().translateAndInsert(c, t, cur);
781 }
782
783
784 int BufferView::workWidth() const
785 {
786         return width_;
787 }
788
789
790 void BufferView::recenter()
791 {
792         showCursor(d->cursor_, true);
793 }
794
795
796 void BufferView::showCursor()
797 {
798         showCursor(d->cursor_, false);
799 }
800
801
802 void BufferView::showCursor(DocIterator const & dit, bool recenter)
803 {
804         if (scrollToCursor(dit, recenter))
805                 buffer_.changed();
806 }
807
808
809 void BufferView::scrollToCursor()
810 {
811         scrollToCursor(d->cursor_, false);
812 }
813
814
815 bool BufferView::scrollToCursor(DocIterator const & dit, bool recenter)
816 {
817         // We are not properly started yet, delay until resizing is
818         // done.
819         if (height_ == 0)
820                 return false;
821
822         LYXERR(Debug::SCROLLING, "recentering!");
823
824         CursorSlice const & bot = dit.bottom();
825         TextMetrics & tm = d->text_metrics_[bot.text()];
826
827         pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
828         int bot_pit = bot.pit();
829         if (bot_pit > max_pit) {
830                 // FIXME: Why does this happen?
831                 LYXERR0("bottom pit is greater that max pit: "
832                         << bot_pit << " > " << max_pit);
833                 bot_pit = max_pit;
834         }
835
836         if (bot_pit == tm.first().first - 1)
837                 tm.newParMetricsUp();
838         else if (bot_pit == tm.last().first + 1)
839                 tm.newParMetricsDown();
840
841         if (tm.contains(bot_pit)) {
842                 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
843                 LASSERT(!pm.rows().empty(), /**/);
844                 // FIXME: smooth scrolling doesn't work in mathed.
845                 CursorSlice const & cs = dit.innerTextSlice();
846                 int offset = coordOffset(dit, dit.boundary()).y_;
847                 int ypos = pm.position() + offset;
848                 Dimension const & row_dim =
849                         pm.getRow(cs.pos(), dit.boundary()).dimension();
850                 int scrolled = 0;
851                 if (recenter)
852                         scrolled = scroll(ypos - height_/2);
853                 else if (ypos - row_dim.ascent() < 0)
854                         scrolled = scrollUp(- ypos + row_dim.ascent());
855                 else if (ypos + row_dim.descent() > height_)
856                         scrolled = scrollDown(ypos - height_ + defaultRowHeight() ); 
857
858                 // else, nothing to do, the cursor is already visible so we just return.
859                 if (scrolled != 0) {
860                         updateMetrics();
861                         return true;
862                 }
863                 return false;
864         }
865
866         // fix inline completion position
867         if (d->inlineCompletionPos_.fixIfBroken())
868                 d->inlineCompletionPos_ = DocIterator();
869
870         tm.redoParagraph(bot_pit);
871         ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
872         int offset = coordOffset(dit, dit.boundary()).y_;
873
874         d->anchor_pit_ = bot_pit;
875         CursorSlice const & cs = dit.innerTextSlice();
876         Dimension const & row_dim =
877                 pm.getRow(cs.pos(), dit.boundary()).dimension();
878
879         if (recenter)
880                 d->anchor_ypos_ = height_/2;
881         else if (d->anchor_pit_ == 0)
882                 d->anchor_ypos_ = offset + pm.ascent();
883         else if (d->anchor_pit_ == max_pit)
884                 d->anchor_ypos_ = height_ - offset - row_dim.descent();
885         else if (offset > height_)
886                 d->anchor_ypos_ = height_ - offset - defaultRowHeight();
887         else
888                 d->anchor_ypos_ = defaultRowHeight() * 2;
889
890         updateMetrics();
891         return true;
892 }
893
894
895 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
896 {
897         FuncStatus flag;
898
899         Cursor & cur = d->cursor_;
900
901         switch (cmd.action) {
902
903         case LFUN_UNDO:
904                 flag.setEnabled(buffer_.undo().hasUndoStack());
905                 break;
906         case LFUN_REDO:
907                 flag.setEnabled(buffer_.undo().hasRedoStack());
908                 break;
909         case LFUN_FILE_INSERT:
910         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
911         case LFUN_FILE_INSERT_PLAINTEXT:
912         case LFUN_BOOKMARK_SAVE:
913                 // FIXME: Actually, these LFUNS should be moved to Text
914                 flag.setEnabled(cur.inTexted());
915                 break;
916         case LFUN_FONT_STATE:
917         case LFUN_LABEL_INSERT:
918         case LFUN_INFO_INSERT:
919         case LFUN_INSET_EDIT:
920         case LFUN_PARAGRAPH_GOTO:
921         case LFUN_NOTE_NEXT:
922         case LFUN_REFERENCE_NEXT:
923         case LFUN_WORD_FIND:
924         case LFUN_WORD_FINDADV:
925         case LFUN_WORD_REPLACE:
926         case LFUN_MARK_OFF:
927         case LFUN_MARK_ON:
928         case LFUN_MARK_TOGGLE:
929         case LFUN_SCREEN_RECENTER:
930         case LFUN_SCREEN_SHOW_CURSOR:
931         case LFUN_BIBTEX_DATABASE_ADD:
932         case LFUN_BIBTEX_DATABASE_DEL:
933         case LFUN_NOTES_MUTATE:
934         case LFUN_ALL_INSETS_TOGGLE:
935         case LFUN_STATISTICS:
936                 flag.setEnabled(true);
937                 break;
938
939         // @todo Test if current WorkArea is the search WorkArea
940         case LFUN_REGEXP_MODE:
941                 flag.setEnabled(! this->cursor().inRegexped());
942                 break;
943
944         case LFUN_COPY_LABEL_AS_REF: {
945                 // if there is an inset at cursor, see whether it
946                 // handles the lfun
947                 Inset * inset = cur.nextInset();
948                 if (!inset || !inset->getStatus(cur, cmd, flag))
949                         flag.setEnabled(false);
950                 break;
951         }
952
953         case LFUN_NEXT_INSET_TOGGLE: 
954         case LFUN_NEXT_INSET_MODIFY: {
955                 // this is the real function we want to invoke
956                 FuncRequest tmpcmd = cmd;
957                 tmpcmd.action = (cmd.action == LFUN_NEXT_INSET_TOGGLE) 
958                         ? LFUN_INSET_TOGGLE : LFUN_INSET_MODIFY;
959                 // if there is an inset at cursor, see whether it
960                 // handles the lfun, other start from scratch
961                 Inset * inset = cur.nextInset();
962                 if (!inset || !inset->getStatus(cur, tmpcmd, flag))
963                         flag = lyx::getStatus(tmpcmd);
964                 break;
965         }
966
967         case LFUN_LABEL_GOTO: {
968                 flag.setEnabled(!cmd.argument().empty()
969                     || getInsetByCode<InsetRef>(cur, REF_CODE));
970                 break;
971         }
972
973         case LFUN_CHANGES_TRACK:
974                 flag.setEnabled(true);
975                 flag.setOnOff(buffer_.params().trackChanges);
976                 break;
977
978         case LFUN_CHANGES_OUTPUT:
979                 flag.setEnabled(true);
980                 flag.setOnOff(buffer_.params().outputChanges);
981                 break;
982
983         case LFUN_CHANGES_MERGE:
984         case LFUN_CHANGE_NEXT:
985         case LFUN_ALL_CHANGES_ACCEPT:
986         case LFUN_ALL_CHANGES_REJECT:
987                 // TODO: context-sensitive enabling of LFUNs
988                 // In principle, these command should only be enabled if there
989                 // is a change in the document. However, without proper
990                 // optimizations, this will inevitably result in poor performance.
991                 flag.setEnabled(true);
992                 break;
993
994         case LFUN_BUFFER_TOGGLE_COMPRESSION: {
995                 flag.setOnOff(buffer_.params().compressed);
996                 break;
997         }
998         
999         case LFUN_SCREEN_UP:
1000         case LFUN_SCREEN_DOWN:
1001         case LFUN_SCROLL:
1002         case LFUN_SCREEN_UP_SELECT:
1003         case LFUN_SCREEN_DOWN_SELECT:
1004                 flag.setEnabled(true);
1005                 break;
1006
1007         case LFUN_LAYOUT_TABULAR:
1008                 flag.setEnabled(cur.innerInsetOfType(TABULAR_CODE));
1009                 break;
1010
1011         case LFUN_LAYOUT:
1012                 flag.setEnabled(!cur.inset().forcePlainLayout(cur.idx()));
1013                 break;
1014
1015         case LFUN_LAYOUT_PARAGRAPH:
1016                 flag.setEnabled(cur.inset().allowParagraphCustomization(cur.idx()));
1017                 break;
1018
1019         case LFUN_INSET_SETTINGS: {
1020                 InsetCode code = cur.inset().lyxCode();
1021                 if (cmd.getArg(0) == insetName(code)) {
1022                         flag.setEnabled(true);
1023                         break;
1024                 }
1025                 bool enable = false;
1026                 InsetCode next_code = cur.nextInset()
1027                         ? cur.nextInset()->lyxCode() : NO_CODE;
1028                 //FIXME: remove these special cases:
1029                 switch (next_code) {
1030                         case TABULAR_CODE:
1031                         case ERT_CODE:
1032                         case FLOAT_CODE:
1033                         case WRAP_CODE:
1034                         case NOTE_CODE:
1035                         case BRANCH_CODE:
1036                         case PHANTOM_CODE:
1037                         case BOX_CODE:
1038                         case LISTINGS_CODE:
1039                                 enable = (cmd.argument().empty() ||
1040                                           cmd.getArg(0) == insetName(next_code));
1041                                 break;
1042                         default:
1043                                 break;
1044                 }
1045                 flag.setEnabled(enable);
1046                 break;
1047         }
1048
1049         case LFUN_DIALOG_SHOW_NEW_INSET:
1050                 flag.setEnabled(cur.inset().lyxCode() != ERT_CODE &&
1051                         cur.inset().lyxCode() != LISTINGS_CODE);
1052                 if (cur.inset().lyxCode() == CAPTION_CODE) {
1053                         FuncStatus flag;
1054                         if (cur.inset().getStatus(cur, cmd, flag))
1055                                 return flag;
1056                 }
1057                 break;
1058
1059         case LFUN_BRANCH_ACTIVATE: 
1060         case LFUN_BRANCH_DEACTIVATE: {
1061                 bool enable = false;
1062                 docstring const branchName = cmd.argument();
1063                 if (!branchName.empty())
1064                         enable = buffer_.params().branchlist().find(branchName);
1065                 flag.setEnabled(enable);
1066                 break;
1067         }
1068
1069         default:
1070                 flag.setEnabled(false);
1071         }
1072
1073         return flag;
1074 }
1075
1076
1077 bool BufferView::dispatch(FuncRequest const & cmd)
1078 {
1079         //lyxerr << [ cmd = " << cmd << "]" << endl;
1080
1081         // Make sure that the cached BufferView is correct.
1082         LYXERR(Debug::ACTION, " action[" << cmd.action << ']'
1083                 << " arg[" << to_utf8(cmd.argument()) << ']'
1084                 << " x[" << cmd.x << ']'
1085                 << " y[" << cmd.y << ']'
1086                 << " button[" << cmd.button() << ']');
1087
1088         Cursor & cur = d->cursor_;
1089
1090         switch (cmd.action) {
1091
1092         case LFUN_UNDO:
1093                 cur.message(_("Undo"));
1094                 cur.clearSelection();
1095                 if (!cur.textUndo())
1096                         cur.message(_("No further undo information"));
1097                 else
1098                         processUpdateFlags(Update::Force | Update::FitCursor);
1099                 break;
1100
1101         case LFUN_REDO:
1102                 cur.message(_("Redo"));
1103                 cur.clearSelection();
1104                 if (!cur.textRedo())
1105                         cur.message(_("No further redo information"));
1106                 else
1107                         processUpdateFlags(Update::Force | Update::FitCursor);
1108                 break;
1109
1110         case LFUN_FONT_STATE:
1111                 cur.message(cur.currentState());
1112                 break;
1113
1114         case LFUN_BOOKMARK_SAVE:
1115                 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1116                 break;
1117
1118         case LFUN_LABEL_GOTO: {
1119                 docstring label = cmd.argument();
1120                 if (label.empty()) {
1121                         InsetRef * inset =
1122                                 getInsetByCode<InsetRef>(d->cursor_, REF_CODE);
1123                         if (inset) {
1124                                 label = inset->getParam("reference");
1125                                 // persistent=false: use temp_bookmark
1126                                 saveBookmark(0);
1127                         }
1128                 }
1129                 if (!label.empty())
1130                         gotoLabel(label);
1131                 break;
1132         }
1133         
1134         case LFUN_INSET_EDIT: {
1135                 FuncRequest fr(cmd);
1136                 // if there is an inset at cursor, see whether it
1137                 // can be modified.
1138                 Inset * inset = cur.nextInset();
1139                 if (inset)
1140                         inset->dispatch(cur, fr);
1141                 // if it did not work, try the underlying inset.
1142                 if (!inset || !cur.result().dispatched())
1143                         cur.dispatch(cmd);
1144
1145                 // FIXME I'm adding the last break to solve a crash,
1146                 // but that is obviously not right.
1147                 if (!cur.result().dispatched())
1148                         // It did not work too; no action needed.
1149                         break;
1150                 break;
1151         }
1152
1153         case LFUN_PARAGRAPH_GOTO: {
1154                 int const id = convert<int>(cmd.getArg(0));
1155                 int const pos = convert<int>(cmd.getArg(1));
1156                 int i = 0;
1157                 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1158                         b = theBufferList().next(b)) {
1159
1160                         DocIterator dit = b->getParFromID(id);
1161                         if (dit.atEnd()) {
1162                                 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1163                                 ++i;
1164                                 continue;
1165                         }
1166                         LYXERR(Debug::INFO, "Paragraph " << dit.paragraph().id()
1167                                 << " found in buffer `"
1168                                 << b->absFileName() << "'.");
1169
1170                         if (b == &buffer_) {
1171                                 // Set the cursor
1172                                 dit.pos() = pos;
1173                                 setCursor(dit);
1174                                 processUpdateFlags(Update::Force | Update::FitCursor);
1175                         } else {
1176                                 // Switch to other buffer view and resend cmd
1177                                 theLyXFunc().dispatch(FuncRequest(
1178                                         LFUN_BUFFER_SWITCH, b->absFileName()));
1179                                 theLyXFunc().dispatch(cmd);
1180                         }
1181                         break;
1182                 }
1183                 break;
1184         }
1185
1186         case LFUN_NOTE_NEXT:
1187                 gotoInset(this, NOTE_CODE, false);
1188                 break;
1189
1190         case LFUN_REFERENCE_NEXT: {
1191                 vector<InsetCode> tmp;
1192                 tmp.push_back(LABEL_CODE);
1193                 tmp.push_back(REF_CODE);
1194                 gotoInset(this, tmp, true);
1195                 break;
1196         }
1197
1198         case LFUN_CHANGES_TRACK:
1199                 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1200                 break;
1201
1202         case LFUN_CHANGES_OUTPUT:
1203                 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1204                 if (buffer_.params().outputChanges) {
1205                         bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
1206                         bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
1207                                           LaTeXFeatures::isAvailable("xcolor");
1208
1209                         if (!dvipost && !xcolorulem) {
1210                                 Alert::warning(_("Changes not shown in LaTeX output"),
1211                                                _("Changes will not be highlighted in LaTeX output, "
1212                                                  "because neither dvipost nor xcolor/ulem are installed.\n"
1213                                                  "Please install these packages or redefine "
1214                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1215                         } else if (!xcolorulem) {
1216                                 Alert::warning(_("Changes not shown in LaTeX output"),
1217                                                _("Changes will not be highlighted in LaTeX output "
1218                                                  "when using pdflatex, because xcolor and ulem are not installed.\n"
1219                                                  "Please install both packages or redefine "
1220                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1221                         }
1222                 }
1223                 break;
1224
1225         case LFUN_CHANGE_NEXT:
1226                 findNextChange(this);
1227                 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1228                 processUpdateFlags(Update::Force | Update::FitCursor);
1229                 break;
1230
1231         case LFUN_CHANGES_MERGE:
1232                 if (findNextChange(this)) {
1233                         processUpdateFlags(Update::Force | Update::FitCursor);
1234                         showDialog("changes");
1235                 }
1236                 break;
1237
1238         case LFUN_ALL_CHANGES_ACCEPT:
1239                 // select complete document
1240                 d->cursor_.reset(buffer_.inset());
1241                 d->cursor_.selHandle(true);
1242                 buffer_.text().cursorBottom(d->cursor_);
1243                 // accept everything in a single step to support atomic undo
1244                 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::ACCEPT);
1245                 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1246                 processUpdateFlags(Update::Force | Update::FitCursor);
1247                 break;
1248
1249         case LFUN_ALL_CHANGES_REJECT:
1250                 // select complete document
1251                 d->cursor_.reset(buffer_.inset());
1252                 d->cursor_.selHandle(true);
1253                 buffer_.text().cursorBottom(d->cursor_);
1254                 // reject everything in a single step to support atomic undo
1255                 // Note: reject does not work recursively; the user may have to repeat the operation
1256                 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::REJECT);
1257                 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1258                 processUpdateFlags(Update::Force | Update::FitCursor);
1259                 break;
1260
1261         case LFUN_WORD_FIND: {
1262                 FuncRequest req = cmd;
1263                 if (cmd.argument().empty() && !d->search_request_cache_.argument().empty())
1264                         req = d->search_request_cache_;
1265                 if (req.argument().empty()) {
1266                         theLyXFunc().dispatch(FuncRequest(LFUN_DIALOG_SHOW, "findreplace"));
1267                         break;
1268                 }
1269                 if (find(this, req))
1270                         showCursor();
1271                 else
1272                         message(_("String not found!"));
1273                 d->search_request_cache_ = req;
1274                 break;
1275         }
1276
1277         case LFUN_WORD_REPLACE: {
1278                 bool has_deleted = false;
1279                 if (cur.selection()) {
1280                         DocIterator beg = cur.selectionBegin();
1281                         DocIterator end = cur.selectionEnd();
1282                         if (beg.pit() == end.pit()) {
1283                                 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1284                                         if (cur.paragraph().isDeleted(p))
1285                                                 has_deleted = true;
1286                                 }
1287                         }
1288                 }
1289                 replace(this, cmd, has_deleted);
1290                 break;
1291         }
1292
1293         case LFUN_WORD_FINDADV:
1294                 findAdv(this, cmd);
1295                 break;
1296
1297         case LFUN_MARK_OFF:
1298                 cur.clearSelection();
1299                 cur.resetAnchor();
1300                 cur.message(from_utf8(N_("Mark off")));
1301                 break;
1302
1303         case LFUN_MARK_ON:
1304                 cur.clearSelection();
1305                 cur.setMark(true);
1306                 cur.resetAnchor();
1307                 cur.message(from_utf8(N_("Mark on")));
1308                 break;
1309
1310         case LFUN_MARK_TOGGLE:
1311                 cur.clearSelection();
1312                 if (cur.mark()) {
1313                         cur.setMark(false);
1314                         cur.message(from_utf8(N_("Mark removed")));
1315                 } else {
1316                         cur.setMark(true);
1317                         cur.message(from_utf8(N_("Mark set")));
1318                 }
1319                 cur.resetAnchor();
1320                 break;
1321
1322         case LFUN_SCREEN_SHOW_CURSOR:
1323                 showCursor();
1324                 break;
1325         
1326         case LFUN_SCREEN_RECENTER:
1327                 recenter();
1328                 break;
1329
1330         case LFUN_BIBTEX_DATABASE_ADD: {
1331                 Cursor tmpcur = d->cursor_;
1332                 findInset(tmpcur, BIBTEX_CODE, false);
1333                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1334                                                 BIBTEX_CODE);
1335                 if (inset) {
1336                         if (inset->addDatabase(cmd.argument()))
1337                                 buffer_.updateBibfilesCache();
1338                 }
1339                 break;
1340         }
1341
1342         case LFUN_BIBTEX_DATABASE_DEL: {
1343                 Cursor tmpcur = d->cursor_;
1344                 findInset(tmpcur, BIBTEX_CODE, false);
1345                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1346                                                 BIBTEX_CODE);
1347                 if (inset) {
1348                         if (inset->delDatabase(cmd.argument()))
1349                                 buffer_.updateBibfilesCache();
1350                 }
1351                 break;
1352         }
1353
1354         case LFUN_STATISTICS: {
1355                 DocIterator from, to;
1356                 if (cur.selection()) {
1357                         from = cur.selectionBegin();
1358                         to = cur.selectionEnd();
1359                 } else {
1360                         from = doc_iterator_begin(&buffer_);
1361                         to = doc_iterator_end(&buffer_);
1362                 }
1363                 int const words = countWords(from, to);
1364                 int const chars = countChars(from, to, false);
1365                 int const chars_blanks = countChars(from, to, true);
1366                 docstring message;
1367                 if (cur.selection())
1368                         message = _("Statistics for the selection:");
1369                 else
1370                         message = _("Statistics for the document:");
1371                 message += "\n\n";
1372                 if (words != 1)
1373                         message += bformat(_("%1$d words"), words);
1374                 else
1375                         message += _("One word");
1376                 message += "\n";
1377                 if (chars_blanks != 1)
1378                         message += bformat(_("%1$d characters (including blanks)"),
1379                                           chars_blanks);
1380                 else
1381                         message += _("One character (including blanks)");
1382                 message += "\n";
1383                 if (chars != 1)
1384                         message += bformat(_("%1$d characters (excluding blanks)"),
1385                                           chars);
1386                 else
1387                         message += _("One character (excluding blanks)");
1388
1389                 Alert::information(_("Statistics"), message);
1390         }
1391                 break;
1392
1393         case LFUN_BUFFER_TOGGLE_COMPRESSION:
1394                 // turn compression on/off
1395                 buffer_.params().compressed = !buffer_.params().compressed;
1396                 break;
1397         case LFUN_COPY_LABEL_AS_REF: {
1398                 // if there is an inset at cursor, try to copy it
1399                 Inset * inset = cur.nextInset();
1400                 if (inset) {
1401                         FuncRequest tmpcmd = cmd;
1402                         inset->dispatch(cur, tmpcmd);
1403                 }
1404                 if (!cur.result().dispatched())
1405                         // It did not work too; no action needed.
1406                         break;
1407                 cur.clearSelection();
1408                 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1409                 break;
1410         }
1411         case LFUN_NEXT_INSET_TOGGLE: {
1412                 // create the the real function we want to invoke
1413                 FuncRequest tmpcmd = cmd;
1414                 tmpcmd.action = LFUN_INSET_TOGGLE;
1415                 // if there is an inset at cursor, see whether it
1416                 // wants to toggle.
1417                 Inset * inset = cur.nextInset();
1418                 if (inset) {
1419                         if (inset->isActive()) {
1420                                 Cursor tmpcur = cur;
1421                                 tmpcur.pushBackward(*inset);
1422                                 inset->dispatch(tmpcur, tmpcmd);
1423                                 if (tmpcur.result().dispatched())
1424                                         cur.dispatched();
1425                         } else 
1426                                 inset->dispatch(cur, tmpcmd);
1427                 }
1428                 // if it did not work, try the underlying inset.
1429                 if (!inset || !cur.result().dispatched())
1430                         cur.dispatch(tmpcmd);
1431
1432                 if (!cur.result().dispatched())
1433                         // It did not work too; no action needed.
1434                         break;
1435                 cur.clearSelection();
1436                 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1437                 break;
1438         }
1439
1440         case LFUN_NEXT_INSET_MODIFY: {
1441                 // create the the real function we want to invoke
1442                 FuncRequest tmpcmd = cmd;
1443                 tmpcmd.action = LFUN_INSET_MODIFY;
1444                 // if there is an inset at cursor, see whether it
1445                 // can be modified.
1446                 Inset * inset = cur.nextInset();
1447                 if (inset) {
1448                         cur.recordUndo();
1449                         inset->dispatch(cur, tmpcmd);
1450                 }
1451                 // if it did not work, try the underlying inset.
1452                 if (!inset || !cur.result().dispatched()) {
1453                         cur.recordUndo();
1454                         cur.dispatch(tmpcmd);
1455                 }
1456
1457                 if (!cur.result().dispatched())
1458                         // It did not work too; no action needed.
1459                         break;
1460                 cur.clearSelection();
1461                 processUpdateFlags(Update::Force | Update::FitCursor);
1462                 break;
1463         }
1464
1465         case LFUN_SCREEN_UP:
1466         case LFUN_SCREEN_DOWN: {
1467                 Point p = getPos(cur, cur.boundary());
1468                 if (p.y_ < 0 || p.y_ > height_) {
1469                         // The cursor is off-screen so recenter before proceeding.
1470                         showCursor();
1471                         p = getPos(cur, cur.boundary());
1472                 }
1473                 int const scrolled = scroll(cmd.action == LFUN_SCREEN_UP
1474                         ? - height_ : height_);
1475                 if (cmd.action == LFUN_SCREEN_UP && scrolled > - height_)
1476                         p = Point(0, 0);
1477                 if (cmd.action == LFUN_SCREEN_DOWN && scrolled < height_)
1478                         p = Point(width_, height_);
1479                 Cursor old = cur;
1480                 bool const in_texted = cur.inTexted();
1481                 cur.reset(buffer_.inset());
1482                 updateMetrics();
1483                 buffer_.changed();
1484                 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1485                 //FIXME: what to do with cur.x_target()?
1486                 bool update = in_texted && cur.bv().checkDepm(cur, old);
1487                 cur.finishUndo();
1488                 if (update)
1489                         processUpdateFlags(Update::Force | Update::FitCursor);
1490                 break;
1491         }
1492
1493         case LFUN_SCROLL:
1494                 lfunScroll(cmd);
1495                 break;
1496
1497         case LFUN_SCREEN_UP_SELECT: {
1498                 cur.selHandle(true);
1499                 if (isTopScreen()) {
1500                         lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
1501                         cur.finishUndo();
1502                         break;
1503                 }
1504                 int y = getPos(cur, cur.boundary()).y_;
1505                 int const ymin = y - height_ + defaultRowHeight();
1506                 while (y > ymin && cur.up())
1507                         y = getPos(cur, cur.boundary()).y_;
1508
1509                 cur.finishUndo();
1510                 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1511                 break;
1512         }
1513
1514         case LFUN_SCREEN_DOWN_SELECT: {
1515                 cur.selHandle(true);
1516                 if (isBottomScreen()) {
1517                         lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
1518                         cur.finishUndo();
1519                         break;
1520                 }
1521                 int y = getPos(cur, cur.boundary()).y_;
1522                 int const ymax = y + height_ - defaultRowHeight();
1523                 while (y < ymax && cur.down())
1524                         y = getPos(cur, cur.boundary()).y_;
1525
1526                 cur.finishUndo();
1527                 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1528                 break;
1529         }
1530
1531         case LFUN_BRANCH_ACTIVATE:
1532         case LFUN_BRANCH_DEACTIVATE:
1533                 buffer_.dispatch(cmd);
1534                 processUpdateFlags(Update::Force);
1535                 break;
1536
1537         // This could be rewriten using some command like forall <insetname> <command>
1538         // once the insets refactoring is done.
1539         case LFUN_NOTES_MUTATE: {
1540                 if (cmd.argument().empty())
1541                         break;
1542
1543                 if (mutateNotes(cur, cmd.getArg(0), cmd.getArg(1))) {
1544                         processUpdateFlags(Update::Force);
1545                 }
1546                 break;
1547         }
1548
1549         case LFUN_ALL_INSETS_TOGGLE: {
1550                 string action;
1551                 string const name = split(to_utf8(cmd.argument()), action, ' ');
1552                 InsetCode const inset_code = insetCode(name);
1553
1554                 FuncRequest fr(LFUN_INSET_TOGGLE, action);
1555
1556                 Inset & inset = cur.buffer()->inset();
1557                 InsetIterator it  = inset_iterator_begin(inset);
1558                 InsetIterator const end = inset_iterator_end(inset);
1559                 for (; it != end; ++it) {
1560                         if (it->asInsetCollapsable()
1561                             && (inset_code == NO_CODE
1562                             || inset_code == it->lyxCode())) {
1563                                 Cursor tmpcur = cur;
1564                                 tmpcur.pushBackward(*it);
1565                                 it->dispatch(tmpcur, fr);
1566                         }
1567                 }
1568                 processUpdateFlags(Update::Force | Update::FitCursor);
1569                 break;
1570         }
1571
1572         default:
1573                 return false;
1574         }
1575
1576         return true;
1577 }
1578
1579
1580 docstring const BufferView::requestSelection()
1581 {
1582         Cursor & cur = d->cursor_;
1583
1584         LYXERR(Debug::SELECTION, "requestSelection: cur.selection: " << cur.selection());
1585         if (!cur.selection()) {
1586                 d->xsel_cache_.set = false;
1587                 return docstring();
1588         }
1589
1590         LYXERR(Debug::SELECTION, "requestSelection: xsel_cache.set: " << d->xsel_cache_.set);
1591         if (!d->xsel_cache_.set ||
1592             cur.top() != d->xsel_cache_.cursor ||
1593             cur.anchor_.top() != d->xsel_cache_.anchor)
1594         {
1595                 d->xsel_cache_.cursor = cur.top();
1596                 d->xsel_cache_.anchor = cur.anchor_.top();
1597                 d->xsel_cache_.set = cur.selection();
1598                 return cur.selectionAsString(false);
1599         }
1600         return docstring();
1601 }
1602
1603
1604 void BufferView::clearSelection()
1605 {
1606         d->cursor_.clearSelection();
1607         // Clear the selection buffer. Otherwise a subsequent
1608         // middle-mouse-button paste would use the selection buffer,
1609         // not the more current external selection.
1610         cap::clearSelection();
1611         d->xsel_cache_.set = false;
1612         // The buffer did not really change, but this causes the
1613         // redraw we need because we cleared the selection above.
1614         buffer_.changed();
1615 }
1616
1617
1618 void BufferView::resize(int width, int height)
1619 {
1620         // Update from work area
1621         width_ = width;
1622         height_ = height;
1623
1624         // Clear the paragraph height cache.
1625         d->par_height_.clear();
1626         // Redo the metrics.
1627         updateMetrics();
1628 }
1629
1630
1631 Inset const * BufferView::getCoveringInset(Text const & text,
1632                 int x, int y) const
1633 {
1634         TextMetrics & tm = d->text_metrics_[&text];
1635         Inset * inset = tm.checkInsetHit(x, y);
1636         if (!inset)
1637                 return 0;
1638
1639         if (!inset->descendable())
1640                 // No need to go further down if the inset is not
1641                 // descendable.
1642                 return inset;
1643
1644         size_t cell_number = inset->nargs();
1645         // Check all the inner cell.
1646         for (size_t i = 0; i != cell_number; ++i) {
1647                 Text const * inner_text = inset->getText(i);
1648                 if (inner_text) {
1649                         // Try deeper.
1650                         Inset const * inset_deeper =
1651                                 getCoveringInset(*inner_text, x, y);
1652                         if (inset_deeper)
1653                                 return inset_deeper;
1654                 }
1655         }
1656
1657         return inset;
1658 }
1659
1660
1661 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1662 {
1663         //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
1664
1665         // This is only called for mouse related events including
1666         // LFUN_FILE_OPEN generated by drag-and-drop.
1667         FuncRequest cmd = cmd0;
1668
1669         Cursor old = cursor();
1670         Cursor cur(*this);
1671         cur.push(buffer_.inset());
1672         cur.setSelection(d->cursor_.selection());
1673
1674         // Either the inset under the cursor or the
1675         // surrounding Text will handle this event.
1676
1677         // make sure we stay within the screen...
1678         cmd.y = min(max(cmd.y, -1), height_);
1679
1680         if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1681
1682                 // Get inset under mouse, if there is one.
1683                 Inset const * covering_inset =
1684                         getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1685                 if (covering_inset == d->last_inset_)
1686                         // Same inset, no need to do anything...
1687                         return;
1688
1689                 bool need_redraw = false;
1690                 // const_cast because of setMouseHover().
1691                 Inset * inset = const_cast<Inset *>(covering_inset);
1692                 if (d->last_inset_)
1693                         // Remove the hint on the last hovered inset (if any).
1694                         need_redraw |= d->last_inset_->setMouseHover(false);
1695                 if (inset)
1696                         // Highlighted the newly hovered inset (if any).
1697                         need_redraw |= inset->setMouseHover(true);
1698                 d->last_inset_ = inset;
1699                 if (!need_redraw)
1700                         return;
1701
1702                 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
1703                         << cmd.x << ", " << cmd.y << ")");
1704
1705                 d->update_strategy_ = DecorationUpdate;
1706
1707                 // This event (moving without mouse click) is not passed further.
1708                 // This should be changed if it is further utilized.
1709                 buffer_.changed();
1710                 return;
1711         }
1712
1713         // Build temporary cursor.
1714         Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1715
1716         // Put anchor at the same position.
1717         cur.resetAnchor();
1718
1719         cur.beginUndoGroup();
1720
1721         // Try to dispatch to an non-editable inset near this position
1722         // via the temp cursor. If the inset wishes to change the real
1723         // cursor it has to do so explicitly by using
1724         //  cur.bv().cursor() = cur;  (or similar)
1725         if (inset)
1726                 inset->dispatch(cur, cmd);
1727
1728         // Now dispatch to the temporary cursor. If the real cursor should
1729         // be modified, the inset's dispatch has to do so explicitly.
1730         if (!inset || !cur.result().dispatched())
1731                 cur.dispatch(cmd);
1732
1733         cur.endUndoGroup();
1734
1735         // Notify left insets
1736         if (cur != old) {
1737                 old.fixIfBroken();
1738                 bool badcursor = notifyCursorLeavesOrEnters(old, cur);
1739                 if (badcursor)
1740                         cursor().fixIfBroken();
1741         }
1742         
1743         // Do we have a selection?
1744         theSelection().haveSelection(cursor().selection());
1745
1746         // If the command has been dispatched,
1747         if (cur.result().dispatched() || cur.result().update())
1748                 processUpdateFlags(cur.result().update());
1749 }
1750
1751
1752 void BufferView::lfunScroll(FuncRequest const & cmd)
1753 {
1754         string const scroll_type = cmd.getArg(0);
1755         int const scroll_step = 
1756                 (scroll_type == "line") ? d->scrollbarParameters_.single_step
1757                 : (scroll_type == "page") ? d->scrollbarParameters_.page_step : 0;
1758         if (scroll_step == 0)
1759                 return;
1760         string const scroll_quantity = cmd.getArg(1);
1761         if (scroll_quantity == "up")
1762                 scrollUp(scroll_step);
1763         else if (scroll_quantity == "down")
1764                 scrollDown(scroll_step);
1765         else {
1766                 int const scroll_value = convert<int>(scroll_quantity);
1767                 if (scroll_value)
1768                         scroll(scroll_step * scroll_value);
1769         }
1770         updateMetrics();
1771         buffer_.changed();
1772 }
1773
1774
1775 int BufferView::scroll(int y)
1776 {
1777         if (y > 0)
1778                 return scrollDown(y);
1779         if (y < 0)
1780                 return scrollUp(-y);
1781         return 0;
1782 }
1783
1784
1785 int BufferView::scrollDown(int offset)
1786 {
1787         Text * text = &buffer_.text();
1788         TextMetrics & tm = d->text_metrics_[text];
1789         int ymax = height_ + offset;
1790         while (true) {
1791                 pair<pit_type, ParagraphMetrics const *> last = tm.last();
1792                 int bottom_pos = last.second->position() + last.second->descent();
1793                 if (last.first + 1 == int(text->paragraphs().size())) {
1794                         if (bottom_pos <= height_)
1795                                 return 0;
1796                         offset = min(offset, bottom_pos - height_);
1797                         break;
1798                 }
1799                 if (bottom_pos > ymax)
1800                         break;
1801                 tm.newParMetricsDown();
1802         }
1803         d->anchor_ypos_ -= offset;
1804         return -offset;
1805 }
1806
1807
1808 int BufferView::scrollUp(int offset)
1809 {
1810         Text * text = &buffer_.text();
1811         TextMetrics & tm = d->text_metrics_[text];
1812         int ymin = - offset;
1813         while (true) {
1814                 pair<pit_type, ParagraphMetrics const *> first = tm.first();
1815                 int top_pos = first.second->position() - first.second->ascent();
1816                 if (first.first == 0) {
1817                         if (top_pos >= 0)
1818                                 return 0;
1819                         offset = min(offset, - top_pos);
1820                         break;
1821                 }
1822                 if (top_pos < ymin)
1823                         break;
1824                 tm.newParMetricsUp();
1825         }
1826         d->anchor_ypos_ += offset;
1827         return offset;
1828 }
1829
1830
1831 void BufferView::setCursorFromRow(int row)
1832 {
1833         int tmpid = -1;
1834         int tmppos = -1;
1835
1836         buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1837
1838         d->cursor_.reset(buffer_.inset());
1839         if (tmpid == -1)
1840                 buffer_.text().setCursor(d->cursor_, 0, 0);
1841         else
1842                 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1843 }
1844
1845
1846 bool BufferView::setCursorFromInset(Inset const * inset)
1847 {
1848         // are we already there?
1849         if (cursor().nextInset() == inset)
1850                 return true;
1851
1852         // Inset is not at cursor position. Find it in the document.
1853         Cursor cur(*this);
1854         cur.reset(buffer().inset());
1855         while (cur && cur.nextInset() != inset)
1856                 cur.forwardInset();
1857
1858         if (cur) {
1859                 setCursor(cur);
1860                 return true;
1861         }
1862         return false;
1863 }
1864
1865
1866 void BufferView::gotoLabel(docstring const & label)
1867 {
1868         std::vector<Buffer const *> bufs = buffer().allRelatives();
1869         std::vector<Buffer const *>::iterator it = bufs.begin();
1870         for (; it != bufs.end(); ++it) {
1871                 Buffer const * buf = *it;
1872
1873                 // find label
1874                 Toc & toc = buf->tocBackend().toc("label");
1875                 TocIterator toc_it = toc.begin();
1876                 TocIterator end = toc.end();
1877                 for (; toc_it != end; ++toc_it) {
1878                         if (label == toc_it->str()) {
1879                                 dispatch(toc_it->action());
1880                                 return;
1881                         }
1882                 }
1883         }
1884 }
1885
1886
1887 TextMetrics const & BufferView::textMetrics(Text const * t) const
1888 {
1889         return const_cast<BufferView *>(this)->textMetrics(t);
1890 }
1891
1892
1893 TextMetrics & BufferView::textMetrics(Text const * t)
1894 {
1895         TextMetricsCache::iterator tmc_it  = d->text_metrics_.find(t);
1896         if (tmc_it == d->text_metrics_.end()) {
1897                 tmc_it = d->text_metrics_.insert(
1898                         make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1899         }
1900         return tmc_it->second;
1901 }
1902
1903
1904 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1905                 pit_type pit) const
1906 {
1907         return textMetrics(t).parMetrics(pit);
1908 }
1909
1910
1911 int BufferView::workHeight() const
1912 {
1913         return height_;
1914 }
1915
1916
1917 void BufferView::setCursor(DocIterator const & dit)
1918 {
1919         size_t const n = dit.depth();
1920         for (size_t i = 0; i < n; ++i)
1921                 dit[i].inset().edit(d->cursor_, true);
1922
1923         d->cursor_.setCursor(dit);
1924         d->cursor_.setSelection(false);
1925 }
1926
1927
1928 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1929 {
1930         // Would be wrong to delete anything if we have a selection.
1931         if (cur.selection())
1932                 return false;
1933
1934         bool need_anchor_change = false;
1935         bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1936                 need_anchor_change);
1937
1938         if (need_anchor_change)
1939                 cur.resetAnchor();
1940
1941         if (!changed)
1942                 return false;
1943
1944         d->cursor_ = cur;
1945
1946         buffer_.updateLabels();
1947
1948         updateMetrics();
1949         buffer_.changed();
1950         return true;
1951 }
1952
1953
1954 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
1955 {
1956         LASSERT(&cur.bv() == this, /**/);
1957
1958         if (!select)
1959                 // this event will clear selection so we save selection for
1960                 // persistent selection
1961                 cap::saveSelection(cursor());
1962
1963         // Has the cursor just left the inset?
1964         bool leftinset = (&d->cursor_.inset() != &cur.inset());
1965         if (leftinset)
1966                 d->cursor_.fixIfBroken();
1967
1968         // FIXME: shift-mouse selection doesn't work well across insets.
1969         bool do_selection = select && &d->cursor_.anchor().inset() == &cur.inset();
1970
1971         // do the dEPM magic if needed
1972         // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1973         // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1974         // the leftinset bool would not be necessary (badcursor instead).
1975         bool update = leftinset;
1976         if (!do_selection && d->cursor_.inTexted())
1977                 update |= checkDepm(cur, d->cursor_);
1978
1979         d->cursor_.setCursor(cur);
1980         d->cursor_.boundary(cur.boundary());
1981         if (do_selection)
1982                 d->cursor_.setSelection();
1983         else
1984                 d->cursor_.clearSelection();
1985
1986         d->cursor_.finishUndo();
1987         d->cursor_.setCurrentFont();
1988         return update;
1989 }
1990
1991
1992 void BufferView::putSelectionAt(DocIterator const & cur,
1993                                 int length, bool backwards)
1994 {
1995         d->cursor_.clearSelection();
1996
1997         setCursor(cur);
1998
1999         if (length) {
2000                 if (backwards) {
2001                         d->cursor_.pos() += length;
2002                         d->cursor_.setSelection(d->cursor_, -length);
2003                 } else
2004                         d->cursor_.setSelection(d->cursor_, length);
2005         }
2006         // Ensure a redraw happens in any case because the new selection could 
2007         // possibly be on the same screen as the previous selection.
2008         processUpdateFlags(Update::Force | Update::FitCursor);
2009 }
2010
2011
2012 Cursor & BufferView::cursor()
2013 {
2014         return d->cursor_;
2015 }
2016
2017
2018 Cursor const & BufferView::cursor() const
2019 {
2020         return d->cursor_;
2021 }
2022
2023
2024 pit_type BufferView::anchor_ref() const
2025 {
2026         return d->anchor_pit_;
2027 }
2028
2029
2030 bool BufferView::singleParUpdate()
2031 {
2032         Text & buftext = buffer_.text();
2033         pit_type const bottom_pit = d->cursor_.bottom().pit();
2034         TextMetrics & tm = textMetrics(&buftext);
2035         int old_height = tm.parMetrics(bottom_pit).height();
2036
2037         // make sure inline completion pointer is ok
2038         if (d->inlineCompletionPos_.fixIfBroken())
2039                 d->inlineCompletionPos_ = DocIterator();
2040
2041         // In Single Paragraph mode, rebreak only
2042         // the (main text, not inset!) paragraph containing the cursor.
2043         // (if this paragraph contains insets etc., rebreaking will
2044         // recursively descend)
2045         tm.redoParagraph(bottom_pit);
2046         ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);                
2047         if (pm.height() != old_height)
2048                 // Paragraph height has changed so we cannot proceed to
2049                 // the singlePar optimisation.
2050                 return false;
2051
2052         d->update_strategy_ = SingleParUpdate;
2053
2054         LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
2055                 << " y2: " << pm.position() + pm.descent()
2056                 << " pit: " << bottom_pit
2057                 << " singlepar: 1");
2058         return true;
2059 }
2060
2061
2062 void BufferView::updateMetrics()
2063 {
2064         if (height_ == 0 || width_ == 0)
2065                 return;
2066
2067         Text & buftext = buffer_.text();
2068         pit_type const npit = int(buftext.paragraphs().size());
2069
2070         // Clear out the position cache in case of full screen redraw,
2071         d->coord_cache_.clear();
2072
2073         // Clear out paragraph metrics to avoid having invalid metrics
2074         // in the cache from paragraphs not relayouted below
2075         // The complete text metrics will be redone.
2076         d->text_metrics_.clear();
2077
2078         TextMetrics & tm = textMetrics(&buftext);
2079
2080         // make sure inline completion pointer is ok
2081         if (d->inlineCompletionPos_.fixIfBroken())
2082                 d->inlineCompletionPos_ = DocIterator();
2083         
2084         if (d->anchor_pit_ >= npit)
2085                 // The anchor pit must have been deleted...
2086                 d->anchor_pit_ = npit - 1;
2087
2088         // Rebreak anchor paragraph.
2089         tm.redoParagraph(d->anchor_pit_);
2090         ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
2091         
2092         // position anchor
2093         if (d->anchor_pit_ == 0) {
2094                 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
2095                 
2096                 // Complete buffer visible? Then it's easy.
2097                 if (scrollRange == 0)
2098                         d->anchor_ypos_ = anchor_pm.ascent();
2099         
2100                 // FIXME: Some clever handling needed to show
2101                 // the _first_ paragraph up to the top if the cursor is
2102                 // in the first line.
2103         }               
2104         anchor_pm.setPosition(d->anchor_ypos_);
2105
2106         LYXERR(Debug::PAINTING, "metrics: "
2107                 << " anchor pit = " << d->anchor_pit_
2108                 << " anchor ypos = " << d->anchor_ypos_);
2109
2110         // Redo paragraphs above anchor if necessary.
2111         int y1 = d->anchor_ypos_ - anchor_pm.ascent();
2112         // We are now just above the anchor paragraph.
2113         pit_type pit1 = d->anchor_pit_ - 1;
2114         for (; pit1 >= 0 && y1 >= 0; --pit1) {
2115                 tm.redoParagraph(pit1);
2116                 ParagraphMetrics & pm = tm.par_metrics_[pit1];
2117                 y1 -= pm.descent();
2118                 // Save the paragraph position in the cache.
2119                 pm.setPosition(y1);
2120                 y1 -= pm.ascent();
2121         }
2122
2123         // Redo paragraphs below the anchor if necessary.
2124         int y2 = d->anchor_ypos_ + anchor_pm.descent();
2125         // We are now just below the anchor paragraph.
2126         pit_type pit2 = d->anchor_pit_ + 1;
2127         for (; pit2 < npit && y2 <= height_; ++pit2) {
2128                 tm.redoParagraph(pit2);
2129                 ParagraphMetrics & pm = tm.par_metrics_[pit2];
2130                 y2 += pm.ascent();
2131                 // Save the paragraph position in the cache.
2132                 pm.setPosition(y2);
2133                 y2 += pm.descent();
2134         }
2135
2136         LYXERR(Debug::PAINTING, "Metrics: "
2137                 << " anchor pit = " << d->anchor_pit_
2138                 << " anchor ypos = " << d->anchor_ypos_
2139                 << " y1 = " << y1
2140                 << " y2 = " << y2
2141                 << " pit1 = " << pit1
2142                 << " pit2 = " << pit2);
2143
2144         d->update_strategy_ = FullScreenUpdate;
2145
2146         if (lyxerr.debugging(Debug::WORKAREA)) {
2147                 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
2148                 d->coord_cache_.dump();
2149         }
2150 }
2151
2152
2153 void BufferView::insertLyXFile(FileName const & fname)
2154 {
2155         LASSERT(d->cursor_.inTexted(), /**/);
2156
2157         // Get absolute path of file and add ".lyx"
2158         // to the filename if necessary
2159         FileName filename = fileSearch(string(), fname.absFilename(), "lyx");
2160
2161         docstring const disp_fn = makeDisplayPath(filename.absFilename());
2162         // emit message signal.
2163         message(bformat(_("Inserting document %1$s..."), disp_fn));
2164
2165         docstring res;
2166         Buffer buf("", false);
2167         if (buf.loadLyXFile(filename)) {
2168                 ErrorList & el = buffer_.errorList("Parse");
2169                 // Copy the inserted document error list into the current buffer one.
2170                 el = buf.errorList("Parse");
2171                 buffer_.undo().recordUndo(d->cursor_);
2172                 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
2173                                              buf.params().documentClassPtr(), el);
2174                 res = _("Document %1$s inserted.");
2175         } else {
2176                 res = _("Could not insert document %1$s");
2177         }
2178
2179         updateMetrics();
2180         buffer_.changed();
2181         // emit message signal.
2182         message(bformat(res, disp_fn));
2183         buffer_.errors("Parse");
2184 }
2185
2186
2187 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
2188 {
2189         int x = 0;
2190         int y = 0;
2191         int lastw = 0;
2192
2193         // Addup contribution of nested insets, from inside to outside,
2194         // keeping the outer paragraph for a special handling below
2195         for (size_t i = dit.depth() - 1; i >= 1; --i) {
2196                 CursorSlice const & sl = dit[i];
2197                 int xx = 0;
2198                 int yy = 0;
2199                 
2200                 // get relative position inside sl.inset()
2201                 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
2202                 
2203                 // Make relative position inside of the edited inset relative to sl.inset()
2204                 x += xx;
2205                 y += yy;
2206                 
2207                 // In case of an RTL inset, the edited inset will be positioned to the left
2208                 // of xx:yy
2209                 if (sl.text()) {
2210                         bool boundary_i = boundary && i + 1 == dit.depth();
2211                         bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
2212                         if (rtl)
2213                                 x -= lastw;
2214                 }
2215
2216                 // remember width for the case that sl.inset() is positioned in an RTL inset
2217                 if (i && dit[i - 1].text()) {
2218                         // If this Inset is inside a Text Inset, retrieve the Dimension
2219                         // from the containing text instead of using Inset::dimension() which
2220                         // might not be implemented.
2221                         // FIXME (Abdel 23/09/2007): this is a bit messy because of the
2222                         // elimination of Inset::dim_ cache. This coordOffset() method needs
2223                         // to be rewritten in light of the new design.
2224                         Dimension const & dim = parMetrics(dit[i - 1].text(),
2225                                 dit[i - 1].pit()).insetDimension(&sl.inset());
2226                         lastw = dim.wid;
2227                 } else {
2228                         Dimension const dim = sl.inset().dimension(*this);
2229                         lastw = dim.wid;
2230                 }
2231                 
2232                 //lyxerr << "Cursor::getPos, i: "
2233                 // << i << " x: " << xx << " y: " << y << endl;
2234         }
2235
2236         // Add contribution of initial rows of outermost paragraph
2237         CursorSlice const & sl = dit[0];
2238         TextMetrics const & tm = textMetrics(sl.text());
2239         ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
2240         LASSERT(!pm.rows().empty(), /**/);
2241         y -= pm.rows()[0].ascent();
2242 #if 1
2243         // FIXME: document this mess
2244         size_t rend;
2245         if (sl.pos() > 0 && dit.depth() == 1) {
2246                 int pos = sl.pos();
2247                 if (pos && boundary)
2248                         --pos;
2249 //              lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
2250                 rend = pm.pos2row(pos);
2251         } else
2252                 rend = pm.pos2row(sl.pos());
2253 #else
2254         size_t rend = pm.pos2row(sl.pos());
2255 #endif
2256         for (size_t rit = 0; rit != rend; ++rit)
2257                 y += pm.rows()[rit].height();
2258         y += pm.rows()[rend].ascent();
2259         
2260         TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
2261         
2262         // Make relative position from the nested inset now bufferview absolute.
2263         int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
2264         x += xx;
2265         
2266         // In the RTL case place the nested inset at the left of the cursor in 
2267         // the outer paragraph
2268         bool boundary_1 = boundary && 1 == dit.depth();
2269         bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
2270         if (rtl)
2271                 x -= lastw;
2272         
2273         return Point(x, y);
2274 }
2275
2276
2277 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
2278 {
2279         if (!paragraphVisible(dit))
2280                 return Point(-1, -1);
2281
2282         CursorSlice const & bot = dit.bottom();
2283         TextMetrics const & tm = textMetrics(bot.text());
2284
2285         Point p = coordOffset(dit, boundary); // offset from outer paragraph
2286         p.y_ += tm.parMetrics(bot.pit()).position();
2287         return p;
2288 }
2289
2290
2291 bool BufferView::paragraphVisible(DocIterator const & dit) const
2292 {
2293         CursorSlice const & bot = dit.bottom();
2294         TextMetrics const & tm = textMetrics(bot.text());
2295
2296         return tm.contains(bot.pit());
2297 }
2298
2299
2300 void BufferView::draw(frontend::Painter & pain)
2301 {
2302         if (height_ == 0 || width_ == 0)
2303                 return;
2304         LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
2305
2306         Text & text = buffer_.text();
2307         TextMetrics const & tm = d->text_metrics_[&text];
2308         int const y = tm.first().second->position();
2309         PainterInfo pi(this, pain);
2310
2311         switch (d->update_strategy_) {
2312
2313         case NoScreenUpdate:
2314                 // If no screen painting is actually needed, only some the different
2315                 // coordinates of insets and paragraphs needs to be updated.
2316                 pi.full_repaint = true;
2317                 pi.pain.setDrawingEnabled(false);
2318                 tm.draw(pi, 0, y);
2319                 break;
2320
2321         case SingleParUpdate:
2322                 pi.full_repaint = false;
2323                 // In general, only the current row of the outermost paragraph
2324                 // will be redrawn. Particular cases where selection spans
2325                 // multiple paragraph are correctly detected in TextMetrics.
2326                 tm.draw(pi, 0, y);
2327                 break;
2328
2329         case DecorationUpdate:
2330                 // FIXME: We should also distinguish DecorationUpdate to avoid text
2331                 // drawing if possible. This is not possible to do easily right now
2332                 // because of the single backing pixmap.
2333
2334         case FullScreenUpdate:
2335                 // The whole screen, including insets, will be refreshed.
2336                 pi.full_repaint = true;
2337
2338                 // Clear background.
2339                 pain.fillRectangle(0, 0, width_, height_,
2340                         pi.backgroundColor(&buffer_.inset()));
2341
2342                 // Draw everything.
2343                 tm.draw(pi, 0, y);
2344
2345                 // and possibly grey out below
2346                 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2347                 int const y2 = lastpm.second->position() + lastpm.second->descent();
2348                 if (y2 < height_)
2349                         pain.fillRectangle(0, y2, width_, height_ - y2, Color_bottomarea);
2350                 break;
2351         }
2352         LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING  ***");
2353
2354         // The scrollbar needs an update.
2355         updateScrollbar();
2356
2357         // Normalize anchor for next time
2358         pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
2359         pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2360         for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
2361                 ParagraphMetrics const & pm = tm.parMetrics(pit);
2362                 if (pm.position() + pm.descent() > 0) {
2363                         d->anchor_pit_ = pit;
2364                         d->anchor_ypos_ = pm.position();
2365                         break;
2366                 }
2367         }
2368         LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
2369                 << "  anchor ypos = " << d->anchor_ypos_);
2370 }
2371
2372
2373 void BufferView::message(docstring const & msg)
2374 {
2375         if (d->gui_)
2376                 d->gui_->message(msg);
2377 }
2378
2379
2380 void BufferView::showDialog(string const & name)
2381 {
2382         if (d->gui_)
2383                 d->gui_->showDialog(name, string());
2384 }
2385
2386
2387 void BufferView::showDialog(string const & name,
2388         string const & data, Inset * inset)
2389 {
2390         if (d->gui_)
2391                 d->gui_->showDialog(name, data, inset);
2392 }
2393
2394
2395 void BufferView::updateDialog(string const & name, string const & data)
2396 {
2397         if (d->gui_)
2398                 d->gui_->updateDialog(name, data);
2399 }
2400
2401
2402 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2403 {
2404         d->gui_ = gui;
2405 }
2406
2407
2408 // FIXME: Move this out of BufferView again
2409 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
2410 {
2411         if (!fname.isReadableFile()) {
2412                 docstring const error = from_ascii(strerror(errno));
2413                 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2414                 docstring const text =
2415                   bformat(_("Could not read the specified document\n"
2416                             "%1$s\ndue to the error: %2$s"), file, error);
2417                 Alert::error(_("Could not read file"), text);
2418                 return docstring();
2419         }
2420
2421         if (!fname.isReadableFile()) {
2422                 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2423                 docstring const text =
2424                   bformat(_("%1$s\n is not readable."), file);
2425                 Alert::error(_("Could not open file"), text);
2426                 return docstring();
2427         }
2428
2429         // FIXME UNICODE: We don't know the encoding of the file
2430         docstring file_content = fname.fileContents("UTF-8");
2431         if (file_content.empty()) {
2432                 Alert::error(_("Reading not UTF-8 encoded file"),
2433                              _("The file is not UTF-8 encoded.\n"
2434                                "It will be read as local 8Bit-encoded.\n"
2435                                "If this does not give the correct result\n"
2436                                "then please change the encoding of the file\n"
2437                                "to UTF-8 with a program other than LyX.\n"));
2438                 file_content = fname.fileContents("local8bit");
2439         }
2440
2441         return normalize_c(file_content);
2442 }
2443
2444
2445 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
2446 {
2447         docstring const tmpstr = contentsOfPlaintextFile(f);
2448
2449         if (tmpstr.empty())
2450                 return;
2451
2452         Cursor & cur = cursor();
2453         cap::replaceSelection(cur);
2454         buffer_.undo().recordUndo(cur);
2455         if (asParagraph)
2456                 cur.innerText()->insertStringAsParagraphs(cur, tmpstr);
2457         else
2458                 cur.innerText()->insertStringAsLines(cur, tmpstr);
2459
2460         updateMetrics();
2461         buffer_.changed();
2462 }
2463
2464
2465 docstring const & BufferView::inlineCompletion() const
2466 {
2467         return d->inlineCompletion_;
2468 }
2469
2470
2471 size_t const & BufferView::inlineCompletionUniqueChars() const
2472 {
2473         return d->inlineCompletionUniqueChars_;
2474 }
2475
2476
2477 DocIterator const & BufferView::inlineCompletionPos() const
2478 {
2479         return d->inlineCompletionPos_;
2480 }
2481
2482
2483 bool samePar(DocIterator const & a, DocIterator const & b)
2484 {
2485         if (a.empty() && b.empty())
2486                 return true;
2487         if (a.empty() || b.empty())
2488                 return false;
2489         if (a.depth() != b.depth())
2490                 return false;
2491         return &a.innerParagraph() == &b.innerParagraph();
2492 }
2493
2494
2495 void BufferView::setInlineCompletion(Cursor & cur, DocIterator const & pos, 
2496         docstring const & completion, size_t uniqueChars)
2497 {
2498         uniqueChars = min(completion.size(), uniqueChars);
2499         bool changed = d->inlineCompletion_ != completion
2500                 || d->inlineCompletionUniqueChars_ != uniqueChars;
2501         bool singlePar = true;
2502         d->inlineCompletion_ = completion;
2503         d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
2504         
2505         //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
2506         
2507         // at new position?
2508         DocIterator const & old = d->inlineCompletionPos_;
2509         if (old != pos) {
2510                 //lyxerr << "inlineCompletionPos changed" << std::endl;
2511                 // old or pos are in another paragraph?
2512                 if ((!samePar(cur, pos) && !pos.empty())
2513                     || (!samePar(cur, old) && !old.empty())) {
2514                         singlePar = false;
2515                         //lyxerr << "different paragraph" << std::endl;
2516                 }
2517                 d->inlineCompletionPos_ = pos;
2518         }
2519         
2520         // set update flags
2521         if (changed) {
2522                 if (singlePar && !(cur.disp_.update() & Update::Force))
2523                         cur.updateFlags(cur.disp_.update() | Update::SinglePar);
2524                 else
2525                         cur.updateFlags(cur.disp_.update() | Update::Force);
2526         }
2527 }
2528
2529 } // namespace lyx