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