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