]> git.lyx.org Git - features.git/blob - src/BufferView.cpp
Move LFUN_ALL_INSETS_TOGGLE dispatch to BufferView.
[features.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                 graphics::Previews::get().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         LyX::ref().session().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         // Get inset under mouse, if there is one.
537         Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
538         if (covering_inset)
539                 return covering_inset->contextMenu(*this, x, y);
540
541         return buffer_.inset().contextMenu(*this, x, y);
542 }
543
544
545 void BufferView::scrollDocView(int value)
546 {
547         int const offset = value - d->scrollbarParameters_.position;
548         // If the offset is less than 2 screen height, prefer to scroll instead.
549         if (abs(offset) <= 2 * height_) {
550                 scroll(offset);
551                 return;
552         }
553
554         // cut off at the top
555         if (value <= d->scrollbarParameters_.min) {
556                 DocIterator dit = doc_iterator_begin(buffer_.inset());
557                 showCursor(dit);
558                 LYXERR(Debug::SCROLLING, "scroll to top");
559                 return;
560         }
561
562         // cut off at the bottom
563         if (value >= d->scrollbarParameters_.max) {
564                 DocIterator dit = doc_iterator_end(buffer_.inset());
565                 dit.backwardPos();
566                 showCursor(dit);
567                 LYXERR(Debug::SCROLLING, "scroll to bottom");
568                 return;
569         }
570
571         // find paragraph at target position
572         int par_pos = d->scrollbarParameters_.min;
573         pit_type i = 0;
574         for (; i != int(d->par_height_.size()); ++i) {
575                 par_pos += d->par_height_[i];
576                 if (par_pos >= value)
577                         break;
578         }
579
580         if (par_pos < value) {
581                 // It seems we didn't find the correct pit so stay on the safe side and
582                 // scroll to bottom.
583                 LYXERR0("scrolling position not found!");
584                 scrollDocView(d->scrollbarParameters_.max);
585                 return;
586         }
587
588         DocIterator dit = doc_iterator_begin(buffer_.inset());
589         dit.pit() = i;
590         LYXERR(Debug::SCROLLING, "value = " << value << " -> scroll to pit " << i);
591         showCursor(dit);
592 }
593
594
595 // FIXME: this method is not working well.
596 void BufferView::setCursorFromScrollbar()
597 {
598         TextMetrics & tm = d->text_metrics_[&buffer_.text()];
599
600         int const height = 2 * defaultRowHeight();
601         int const first = height;
602         int const last = height_ - height;
603         Cursor & cur = d->cursor_;
604
605         switch (cursorStatus(cur)) {
606         case CUR_ABOVE:
607                 // We reset the cursor because cursorStatus() does not
608                 // work when the cursor is within mathed.
609                 cur.reset(buffer_.inset());
610                 tm.setCursorFromCoordinates(cur, 0, first);
611                 cur.clearSelection();
612                 break;
613         case CUR_BELOW:
614                 // We reset the cursor because cursorStatus() does not
615                 // work when the cursor is within mathed.
616                 cur.reset(buffer_.inset());
617                 tm.setCursorFromCoordinates(cur, 0, last);
618                 cur.clearSelection();
619                 break;
620         case CUR_INSIDE:
621                 int const y = getPos(cur, cur.boundary()).y_;
622                 int const newy = min(last, max(y, first));
623                 if (y != newy) {
624                         cur.reset(buffer_.inset());
625                         tm.setCursorFromCoordinates(cur, 0, newy);
626                 }
627         }
628 }
629
630
631 Change const BufferView::getCurrentChange() const
632 {
633         if (!d->cursor_.selection())
634                 return Change(Change::UNCHANGED);
635
636         DocIterator dit = d->cursor_.selectionBegin();
637         return dit.paragraph().lookupChange(dit.pos());
638 }
639
640
641 // this could be used elsewhere as well?
642 // FIXME: This does not work within mathed!
643 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
644 {
645         Point const p = getPos(dit, dit.boundary());
646         if (p.y_ < 0)
647                 return CUR_ABOVE;
648         if (p.y_ > workHeight())
649                 return CUR_BELOW;
650         return CUR_INSIDE;
651 }
652
653
654 void BufferView::saveBookmark(unsigned int idx)
655 {
656         // tenatively save bookmark, id and pos will be used to
657         // acturately locate a bookmark in a 'live' lyx session.
658         // pit and pos will be updated with bottom level pit/pos
659         // when lyx exits.
660         LyX::ref().session().bookmarks().save(
661                 buffer_.fileName(),
662                 d->cursor_.bottom().pit(),
663                 d->cursor_.bottom().pos(),
664                 d->cursor_.paragraph().id(),
665                 d->cursor_.pos(),
666                 idx
667         );
668         if (idx)
669                 // emit message signal.
670                 message(_("Save bookmark"));
671 }
672
673
674 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
675         int top_id, pos_type top_pos)
676 {
677         bool success = false;
678         DocIterator dit;
679
680         d->cursor_.clearSelection();
681
682         // if a valid par_id is given, try it first
683         // This is the case for a 'live' bookmark when unique paragraph ID
684         // is used to track bookmarks.
685         if (top_id > 0) {
686                 dit = buffer_.getParFromID(top_id);
687                 if (!dit.atEnd()) {
688                         dit.pos() = min(dit.paragraph().size(), top_pos);
689                         // Some slices of the iterator may not be
690                         // reachable (e.g. closed collapsable inset)
691                         // so the dociterator may need to be
692                         // shortened. Otherwise, setCursor may crash
693                         // lyx when the cursor can not be set to these
694                         // insets.
695                         size_t const n = dit.depth();
696                         for (size_t i = 0; i < n; ++i)
697                                 if (dit[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
698                                         dit.resize(i);
699                                         break;
700                                 }
701                         success = true;
702                 }
703         }
704
705         // if top_id == 0, or searching through top_id failed
706         // This is the case for a 'restored' bookmark when only bottom
707         // (document level) pit was saved. Because of this, bookmark
708         // restoration is inaccurate. If a bookmark was within an inset,
709         // it will be restored to the left of the outmost inset that contains
710         // the bookmark.
711         if (bottom_pit < int(buffer_.paragraphs().size())) {
712                 dit = doc_iterator_begin(buffer_.inset());
713                                 
714                 dit.pit() = bottom_pit;
715                 dit.pos() = min(bottom_pos, dit.paragraph().size());
716                 success = true;
717         }
718
719         if (success) {
720                 // Note: only bottom (document) level pit is set.
721                 setCursor(dit);
722                 // set the current font.
723                 d->cursor_.setCurrentFont();
724                 // To center the screen on this new position we need the
725                 // paragraph position which is computed at draw() time.
726                 // So we need a redraw!
727                 buffer_.changed();
728                 if (fitCursor())
729                         showCursor();
730         }
731
732         return success;
733 }
734
735
736 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
737 {
738         if (lyxrc.rtl_support) {
739                 if (d->cursor_.real_current_font.isRightToLeft()) {
740                         if (d->intl_.keymap == Intl::PRIMARY)
741                                 d->intl_.keyMapSec();
742                 } else {
743                         if (d->intl_.keymap == Intl::SECONDARY)
744                                 d->intl_.keyMapPrim();
745                 }
746         }
747
748         d->intl_.getTransManager().translateAndInsert(c, t, cur);
749 }
750
751
752 int BufferView::workWidth() const
753 {
754         return width_;
755 }
756
757
758 void BufferView::showCursor()
759 {
760         showCursor(d->cursor_);
761 }
762
763
764 void BufferView::showCursor(DocIterator const & dit)
765 {
766         // We are not properly started yet, delay until resizing is
767         // done.
768         if (height_ == 0)
769                 return;
770
771         LYXERR(Debug::SCROLLING, "recentering!");
772
773         CursorSlice const & bot = dit.bottom();
774         TextMetrics & tm = d->text_metrics_[bot.text()];
775
776         pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
777         int bot_pit = bot.pit();
778         if (bot_pit > max_pit) {
779                 // FIXME: Why does this happen?
780                 LYXERR0("bottom pit is greater that max pit: "
781                         << bot_pit << " > " << max_pit);
782                 bot_pit = max_pit;
783         }
784
785         if (bot_pit == tm.first().first - 1)
786                 tm.newParMetricsUp();
787         else if (bot_pit == tm.last().first + 1)
788                 tm.newParMetricsDown();
789
790         if (tm.contains(bot_pit)) {
791                 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
792                 LASSERT(!pm.rows().empty(), /**/);
793                 // FIXME: smooth scrolling doesn't work in mathed.
794                 CursorSlice const & cs = dit.innerTextSlice();
795                 int offset = coordOffset(dit, dit.boundary()).y_;
796                 int ypos = pm.position() + offset;
797                 Dimension const & row_dim =
798                         pm.getRow(cs.pos(), dit.boundary()).dimension();
799                 if (ypos - row_dim.ascent() < 0)
800                         scrollUp(- ypos + row_dim.ascent());
801                 else if (ypos + row_dim.descent() > height_)
802                         scrollDown(ypos - height_ + row_dim.descent());
803                 // else, nothing to do, the cursor is already visible so we just return.
804                 return;
805         }
806
807         // fix inline completion position
808         if (d->inlineCompletionPos_.fixIfBroken())
809                 d->inlineCompletionPos_ = DocIterator();
810
811         tm.redoParagraph(bot_pit);
812         ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
813         int offset = coordOffset(dit, dit.boundary()).y_;
814
815         d->anchor_pit_ = bot_pit;
816         CursorSlice const & cs = dit.innerTextSlice();
817         Dimension const & row_dim =
818                 pm.getRow(cs.pos(), dit.boundary()).dimension();
819
820         if (d->anchor_pit_ == 0)
821                 d->anchor_ypos_ = offset + pm.ascent();
822         else if (d->anchor_pit_ == max_pit)
823                 d->anchor_ypos_ = height_ - offset - row_dim.descent();
824         else
825                 d->anchor_ypos_ = defaultRowHeight() * 2 - offset - row_dim.descent();
826
827         updateMetrics();
828         buffer_.changed();
829 }
830
831
832 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
833 {
834         FuncStatus flag;
835
836         Cursor & cur = d->cursor_;
837
838         switch (cmd.action) {
839
840         case LFUN_UNDO:
841                 flag.setEnabled(buffer_.undo().hasUndoStack());
842                 break;
843         case LFUN_REDO:
844                 flag.setEnabled(buffer_.undo().hasRedoStack());
845                 break;
846         case LFUN_FILE_INSERT:
847         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
848         case LFUN_FILE_INSERT_PLAINTEXT:
849         case LFUN_BOOKMARK_SAVE:
850                 // FIXME: Actually, these LFUNS should be moved to Text
851                 flag.setEnabled(cur.inTexted());
852                 break;
853         case LFUN_FONT_STATE:
854         case LFUN_LABEL_INSERT:
855         case LFUN_INFO_INSERT:
856         case LFUN_INSET_EDIT:
857         case LFUN_PARAGRAPH_GOTO:
858         case LFUN_NOTE_NEXT:
859         case LFUN_REFERENCE_NEXT:
860         case LFUN_WORD_FIND:
861         case LFUN_WORD_REPLACE:
862         case LFUN_MARK_OFF:
863         case LFUN_MARK_ON:
864         case LFUN_MARK_TOGGLE:
865         case LFUN_SCREEN_RECENTER:
866         case LFUN_BIBTEX_DATABASE_ADD:
867         case LFUN_BIBTEX_DATABASE_DEL:
868         case LFUN_GRAPHICS_GROUPS_UNIFY:
869         case LFUN_NOTES_MUTATE:
870         case LFUN_ALL_INSETS_TOGGLE:
871         case LFUN_STATISTICS:
872                 flag.setEnabled(true);
873                 break;
874
875         case LFUN_NEXT_INSET_TOGGLE: 
876         case LFUN_NEXT_INSET_MODIFY: {
877                 // this is the real function we want to invoke
878                 FuncRequest tmpcmd = cmd;
879                 tmpcmd.action = (cmd.action == LFUN_NEXT_INSET_TOGGLE) 
880                         ? LFUN_INSET_TOGGLE : LFUN_INSET_MODIFY;
881                 // if there is an inset at cursor, see whether it
882                 // handles the lfun, other start from scratch
883                 Inset * inset = cur.nextInset();
884                 if (!inset || !inset->getStatus(cur, tmpcmd, flag))
885                         flag = lyx::getStatus(tmpcmd);
886                 break;
887         }
888
889         case LFUN_LABEL_GOTO: {
890                 flag.setEnabled(!cmd.argument().empty()
891                     || getInsetByCode<InsetRef>(cur, REF_CODE));
892                 break;
893         }
894
895         case LFUN_CHANGES_TRACK:
896                 flag.setEnabled(true);
897                 flag.setOnOff(buffer_.params().trackChanges);
898                 break;
899
900         case LFUN_CHANGES_OUTPUT:
901                 flag.setEnabled(true);
902                 flag.setOnOff(buffer_.params().outputChanges);
903                 break;
904
905         case LFUN_CHANGES_MERGE:
906         case LFUN_CHANGE_NEXT:
907         case LFUN_ALL_CHANGES_ACCEPT:
908         case LFUN_ALL_CHANGES_REJECT:
909                 // TODO: context-sensitive enabling of LFUNs
910                 // In principle, these command should only be enabled if there
911                 // is a change in the document. However, without proper
912                 // optimizations, this will inevitably result in poor performance.
913                 flag.setEnabled(true);
914                 break;
915
916         case LFUN_BUFFER_TOGGLE_COMPRESSION: {
917                 flag.setOnOff(buffer_.params().compressed);
918                 break;
919         }
920         
921         case LFUN_SCREEN_UP:
922         case LFUN_SCREEN_DOWN:
923         case LFUN_SCROLL:
924         case LFUN_SCREEN_UP_SELECT:
925         case LFUN_SCREEN_DOWN_SELECT:
926                 flag.setEnabled(true);
927                 break;
928
929         case LFUN_LAYOUT_TABULAR:
930                 flag.setEnabled(cur.innerInsetOfType(TABULAR_CODE));
931                 break;
932
933         case LFUN_LAYOUT:
934                 flag.setEnabled(!cur.inset().forceEmptyLayout(cur.idx()));
935                 break;
936
937         case LFUN_LAYOUT_PARAGRAPH:
938                 flag.setEnabled(cur.inset().allowParagraphCustomization(cur.idx()));
939                 break;
940
941         case LFUN_INSET_SETTINGS: {
942                 InsetCode code = cur.inset().lyxCode();
943                 if (cmd.getArg(0) == insetName(code)) {
944                         flag.setEnabled(true);
945                         break;
946                 }
947                 bool enable = false;
948                 InsetCode next_code = cur.nextInset()
949                         ? cur.nextInset()->lyxCode() : NO_CODE;
950                 //FIXME: remove these special cases:
951                 switch (next_code) {
952                         case TABULAR_CODE:
953                         case ERT_CODE:
954                         case FLOAT_CODE:
955                         case WRAP_CODE:
956                         case NOTE_CODE:
957                         case BRANCH_CODE:
958                         case BOX_CODE:
959                         case LISTINGS_CODE:
960                                 enable = (cmd.argument().empty() ||
961                                           cmd.getArg(0) == insetName(next_code));
962                                 break;
963                         default:
964                                 break;
965                 }
966                 flag.setEnabled(enable);
967                 break;
968         }
969
970         case LFUN_DIALOG_SHOW_NEW_INSET:
971                 flag.setEnabled(cur.inset().lyxCode() != ERT_CODE &&
972                         cur.inset().lyxCode() != LISTINGS_CODE);
973                 if (cur.inset().lyxCode() == CAPTION_CODE) {
974                         FuncStatus flag;
975                         if (cur.inset().getStatus(cur, cmd, flag))
976                                 return flag;
977                 }
978                 break;
979
980         case LFUN_BRANCH_ACTIVATE: 
981         case LFUN_BRANCH_DEACTIVATE: {
982                 bool enable = false;
983                 docstring const branchName = cmd.argument();
984                 if (!branchName.empty())
985                         enable = buffer_.params().branchlist().find(branchName);
986                 flag.setEnabled(enable);
987                 break;
988         }
989
990         default:
991                 flag.setEnabled(false);
992         }
993
994         return flag;
995 }
996
997
998 bool BufferView::dispatch(FuncRequest const & cmd)
999 {
1000         //lyxerr << [ cmd = " << cmd << "]" << endl;
1001
1002         // Make sure that the cached BufferView is correct.
1003         LYXERR(Debug::ACTION, " action[" << cmd.action << ']'
1004                 << " arg[" << to_utf8(cmd.argument()) << ']'
1005                 << " x[" << cmd.x << ']'
1006                 << " y[" << cmd.y << ']'
1007                 << " button[" << cmd.button() << ']');
1008
1009         Cursor & cur = d->cursor_;
1010
1011         switch (cmd.action) {
1012
1013         case LFUN_UNDO:
1014                 cur.message(_("Undo"));
1015                 cur.clearSelection();
1016                 if (!cur.textUndo())
1017                         cur.message(_("No further undo information"));
1018                 else
1019                         processUpdateFlags(Update::Force | Update::FitCursor);
1020                 break;
1021
1022         case LFUN_REDO:
1023                 cur.message(_("Redo"));
1024                 cur.clearSelection();
1025                 if (!cur.textRedo())
1026                         cur.message(_("No further redo information"));
1027                 else
1028                         processUpdateFlags(Update::Force | Update::FitCursor);
1029                 break;
1030
1031         case LFUN_FONT_STATE:
1032                 cur.message(cur.currentState());
1033                 break;
1034
1035         case LFUN_BOOKMARK_SAVE:
1036                 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1037                 break;
1038
1039         case LFUN_LABEL_GOTO: {
1040                 docstring label = cmd.argument();
1041                 if (label.empty()) {
1042                         InsetRef * inset =
1043                                 getInsetByCode<InsetRef>(d->cursor_,
1044                                                          REF_CODE);
1045                         if (inset) {
1046                                 label = inset->getParam("reference");
1047                                 // persistent=false: use temp_bookmark
1048                                 saveBookmark(0);
1049                         }
1050                 }
1051
1052                 if (!label.empty())
1053                         gotoLabel(label);
1054                 break;
1055         }
1056         
1057         case LFUN_INSET_EDIT: {
1058                 FuncRequest fr(cmd);
1059                 // if there is an inset at cursor, see whether it
1060                 // can be modified.
1061                 Inset * inset = cur.nextInset();
1062                 if (inset)
1063                         inset->dispatch(cur, fr);
1064                 // if it did not work, try the underlying inset.
1065                 if (!inset || !cur.result().dispatched())
1066                         cur.dispatch(cmd);
1067
1068                 if (!cur.result().dispatched())
1069                         // It did not work too; no action needed.
1070                         break;
1071         }
1072
1073         case LFUN_PARAGRAPH_GOTO: {
1074                 int const id = convert<int>(cmd.getArg(0));
1075                 int const pos = convert<int>(cmd.getArg(1));
1076                 int i = 0;
1077                 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1078                         b = theBufferList().next(b)) {
1079
1080                         DocIterator dit = b->getParFromID(id);
1081                         if (dit.atEnd()) {
1082                                 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1083                                 ++i;
1084                                 continue;
1085                         }
1086                         LYXERR(Debug::INFO, "Paragraph " << dit.paragraph().id()
1087                                 << " found in buffer `"
1088                                 << b->absFileName() << "'.");
1089
1090                         if (b == &buffer_) {
1091                                 // Set the cursor
1092                                 dit.pos() = pos;
1093                                 setCursor(dit);
1094                                 processUpdateFlags(Update::Force | Update::FitCursor);
1095                         } else {
1096                                 // Switch to other buffer view and resend cmd
1097                                 theLyXFunc().dispatch(FuncRequest(
1098                                         LFUN_BUFFER_SWITCH, b->absFileName()));
1099                                 theLyXFunc().dispatch(cmd);
1100                         }
1101                         break;
1102                 }
1103                 break;
1104         }
1105
1106         case LFUN_NOTE_NEXT:
1107                 gotoInset(this, NOTE_CODE, false);
1108                 break;
1109
1110         case LFUN_REFERENCE_NEXT: {
1111                 vector<InsetCode> tmp;
1112                 tmp.push_back(LABEL_CODE);
1113                 tmp.push_back(REF_CODE);
1114                 gotoInset(this, tmp, true);
1115                 break;
1116         }
1117
1118         case LFUN_CHANGES_TRACK:
1119                 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1120                 break;
1121
1122         case LFUN_CHANGES_OUTPUT:
1123                 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1124                 if (buffer_.params().outputChanges) {
1125                         bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
1126                         bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1127                                           LaTeXFeatures::isAvailable("xcolor");
1128
1129                         if (!dvipost && !xcolorsoul) {
1130                                 Alert::warning(_("Changes not shown in LaTeX output"),
1131                                                _("Changes will not be highlighted in LaTeX output, "
1132                                                  "because neither dvipost nor xcolor/soul are installed.\n"
1133                                                  "Please install these packages or redefine "
1134                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1135                         } else if (!xcolorsoul) {
1136                                 Alert::warning(_("Changes not shown in LaTeX output"),
1137                                                _("Changes will not be highlighted in LaTeX output "
1138                                                  "when using pdflatex, because xcolor and soul are not installed.\n"
1139                                                  "Please install both packages or redefine "
1140                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1141                         }
1142                 }
1143                 break;
1144
1145         case LFUN_CHANGE_NEXT:
1146                 findNextChange(this);
1147                 break;
1148
1149         case LFUN_CHANGES_MERGE:
1150                 if (findNextChange(this))
1151                         showDialog("changes");
1152                 break;
1153
1154         case LFUN_ALL_CHANGES_ACCEPT:
1155                 // select complete document
1156                 d->cursor_.reset(buffer_.inset());
1157                 d->cursor_.selHandle(true);
1158                 buffer_.text().cursorBottom(d->cursor_);
1159                 // accept everything in a single step to support atomic undo
1160                 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::ACCEPT);
1161                 break;
1162
1163         case LFUN_ALL_CHANGES_REJECT:
1164                 // select complete document
1165                 d->cursor_.reset(buffer_.inset());
1166                 d->cursor_.selHandle(true);
1167                 buffer_.text().cursorBottom(d->cursor_);
1168                 // reject everything in a single step to support atomic undo
1169                 // Note: reject does not work recursively; the user may have to repeat the operation
1170                 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::REJECT);
1171                 break;
1172
1173         case LFUN_WORD_FIND: {
1174                 FuncRequest req = cmd;
1175                 if (cmd.argument().empty() && !d->search_request_cache_.argument().empty())
1176                         req = d->search_request_cache_;
1177                 if (find(this, req))
1178                         showCursor();
1179                 else
1180                         message(_("String not found!"));
1181                 d->search_request_cache_ = req;
1182                 break;
1183         }
1184
1185         case LFUN_WORD_REPLACE: {
1186                 bool has_deleted = false;
1187                 if (cur.selection()) {
1188                         DocIterator beg = cur.selectionBegin();
1189                         DocIterator end = cur.selectionEnd();
1190                         if (beg.pit() == end.pit()) {
1191                                 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1192                                         if (cur.paragraph().isDeleted(p))
1193                                                 has_deleted = true;
1194                                 }
1195                         }
1196                 }
1197                 replace(this, cmd, has_deleted);
1198                 break;
1199         }
1200
1201         case LFUN_MARK_OFF:
1202                 cur.clearSelection();
1203                 cur.resetAnchor();
1204                 cur.message(from_utf8(N_("Mark off")));
1205                 break;
1206
1207         case LFUN_MARK_ON:
1208                 cur.clearSelection();
1209                 cur.mark() = true;
1210                 cur.resetAnchor();
1211                 cur.message(from_utf8(N_("Mark on")));
1212                 break;
1213
1214         case LFUN_MARK_TOGGLE:
1215                 cur.clearSelection();
1216                 if (cur.mark()) {
1217                         cur.mark() = false;
1218                         cur.message(from_utf8(N_("Mark removed")));
1219                 } else {
1220                         cur.mark() = true;
1221                         cur.message(from_utf8(N_("Mark set")));
1222                 }
1223                 cur.resetAnchor();
1224                 break;
1225
1226         case LFUN_SCREEN_RECENTER:
1227                 showCursor();
1228                 break;
1229
1230         case LFUN_BIBTEX_DATABASE_ADD: {
1231                 Cursor tmpcur = d->cursor_;
1232                 findInset(tmpcur, BIBTEX_CODE, false);
1233                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1234                                                 BIBTEX_CODE);
1235                 if (inset) {
1236                         if (inset->addDatabase(cmd.argument()))
1237                                 buffer_.updateBibfilesCache();
1238                 }
1239                 break;
1240         }
1241
1242         case LFUN_BIBTEX_DATABASE_DEL: {
1243                 Cursor tmpcur = d->cursor_;
1244                 findInset(tmpcur, BIBTEX_CODE, false);
1245                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1246                                                 BIBTEX_CODE);
1247                 if (inset) {
1248                         if (inset->delDatabase(cmd.argument()))
1249                                 buffer_.updateBibfilesCache();
1250                 }
1251                 break;
1252         }
1253
1254         case LFUN_STATISTICS: {
1255                 DocIterator from, to;
1256                 if (cur.selection()) {
1257                         from = cur.selectionBegin();
1258                         to = cur.selectionEnd();
1259                 } else {
1260                         from = doc_iterator_begin(buffer_.inset());
1261                         to = doc_iterator_end(buffer_.inset());
1262                 }
1263                 int const words = countWords(from, to);
1264                 int const chars = countChars(from, to, false);
1265                 int const chars_blanks = countChars(from, to, true);
1266                 docstring message;
1267                 if (cur.selection())
1268                         message = _("Statistics for the selection:");
1269                 else
1270                         message = _("Statistics for the document:");
1271                 message += "\n\n";
1272                 if (words != 1)
1273                         message += bformat(_("%1$d words"), words);
1274                 else
1275                         message += _("One word");
1276                 message += "\n";
1277                 if (chars_blanks != 1)
1278                         message += bformat(_("%1$d characters (including blanks)"),
1279                                           chars_blanks);
1280                 else
1281                         message += _("One character (including blanks)");
1282                 message += "\n";
1283                 if (chars != 1)
1284                         message += bformat(_("%1$d characters (excluding blanks)"),
1285                                           chars);
1286                 else
1287                         message += _("One character (excluding blanks)");
1288
1289                 Alert::information(_("Statistics"), message);
1290         }
1291                 break;
1292
1293         case LFUN_BUFFER_TOGGLE_COMPRESSION:
1294                 // turn compression on/off
1295                 buffer_.params().compressed = !buffer_.params().compressed;
1296                 break;
1297         
1298         case LFUN_NEXT_INSET_TOGGLE: {
1299                 // create the the real function we want to invoke
1300                 FuncRequest tmpcmd = cmd;
1301                 tmpcmd.action = LFUN_INSET_TOGGLE;
1302                 // if there is an inset at cursor, see whether it
1303                 // wants to toggle.
1304                 Inset * inset = cur.nextInset();
1305                 if (inset) {
1306                         if (inset->isActive()) {
1307                                 Cursor tmpcur = cur;
1308                                 tmpcur.pushBackward(*inset);
1309                                 inset->dispatch(tmpcur, tmpcmd);
1310                                 if (tmpcur.result().dispatched())
1311                                         cur.dispatched();
1312                         } else 
1313                                 inset->dispatch(cur, tmpcmd);
1314                 }
1315                 // if it did not work, try the underlying inset.
1316                 if (!inset || !cur.result().dispatched())
1317                         cur.dispatch(tmpcmd);
1318
1319                 if (!cur.result().dispatched())
1320                         // It did not work too; no action needed.
1321                         break;
1322                 cur.clearSelection();
1323                 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1324                 break;
1325         }
1326
1327         case LFUN_NEXT_INSET_MODIFY: {
1328                 // create the the real function we want to invoke
1329                 FuncRequest tmpcmd = cmd;
1330                 tmpcmd.action = LFUN_INSET_MODIFY;
1331                 // if there is an inset at cursor, see whether it
1332                 // can be modified.
1333                 Inset * inset = cur.nextInset();
1334                 if (inset)
1335                         inset->dispatch(cur, tmpcmd);
1336                 // if it did not work, try the underlying inset.
1337                 if (!inset || !cur.result().dispatched())
1338                         cur.dispatch(tmpcmd);
1339
1340                 if (!cur.result().dispatched())
1341                         // It did not work too; no action needed.
1342                         break;
1343                 cur.clearSelection();
1344                 processUpdateFlags(Update::Force | Update::FitCursor);
1345                 break;
1346         }
1347
1348         case LFUN_SCREEN_UP:
1349         case LFUN_SCREEN_DOWN: {
1350                 Point p = getPos(cur, cur.boundary());
1351                 if (p.y_ < 0 || p.y_ > height_) {
1352                         // The cursor is off-screen so recenter before proceeding.
1353                         showCursor();
1354                         p = getPos(cur, cur.boundary());
1355                 }
1356                 scroll(cmd.action == LFUN_SCREEN_UP? - height_ : height_);
1357                 cur.reset(buffer_.inset());
1358                 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1359                 //FIXME: what to do with cur.x_target()?
1360                 cur.finishUndo();
1361                 break;
1362         }
1363
1364         case LFUN_SCROLL:
1365                 lfunScroll(cmd);
1366                 break;
1367
1368         case LFUN_SCREEN_UP_SELECT: {
1369                 cur.selHandle(true);
1370                 if (isTopScreen()) {
1371                         lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
1372                         cur.finishUndo();
1373                         break;
1374                 }
1375                 int y = getPos(cur, cur.boundary()).y_;
1376                 int const ymin = y - height_ + defaultRowHeight();
1377                 while (y > ymin && cur.up())
1378                         y = getPos(cur, cur.boundary()).y_;
1379
1380                 cur.finishUndo();
1381                 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1382                 break;
1383         }
1384
1385         case LFUN_SCREEN_DOWN_SELECT: {
1386                 cur.selHandle(true);
1387                 if (isBottomScreen()) {
1388                         lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
1389                         cur.finishUndo();
1390                         break;
1391                 }
1392                 int y = getPos(cur, cur.boundary()).y_;
1393                 int const ymax = y + height_ - defaultRowHeight();
1394                 while (y < ymax && cur.down())
1395                         y = getPos(cur, cur.boundary()).y_;
1396
1397                 cur.finishUndo();
1398                 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1399                 break;
1400         }
1401
1402         case LFUN_BRANCH_ACTIVATE:
1403         case LFUN_BRANCH_DEACTIVATE:
1404                 buffer_.dispatch(cmd);
1405                 processUpdateFlags(Update::Force);
1406                 break;
1407
1408         // These two could be rewriten using some command like forall <insetname> <command>
1409         // once the insets refactoring is done.
1410         case LFUN_GRAPHICS_GROUPS_UNIFY: {
1411                 if (cmd.argument().empty())
1412                         break;
1413                 //view()->cursor().recordUndoFullDocument(); let inset-apply do that job
1414                 graphics::unifyGraphicsGroups(cur.buffer(), to_utf8(cmd.argument()));
1415                 processUpdateFlags(Update::Force | Update::FitCursor);
1416                 break;
1417         }
1418
1419         case LFUN_NOTES_MUTATE: {
1420                 if (cmd.argument().empty())
1421                         break;
1422                 cur.recordUndoFullDocument();
1423
1424                 if (mutateNotes(cur, cmd.getArg(0), cmd.getArg(1))) {
1425                         processUpdateFlags(Update::Force);
1426                 }
1427                 break;
1428         }
1429
1430         case LFUN_ALL_INSETS_TOGGLE: {
1431                 string action;
1432                 string const name = split(to_utf8(cmd.argument()), action, ' ');
1433                 InsetCode const inset_code = insetCode(name);
1434
1435                 FuncRequest fr(LFUN_INSET_TOGGLE, action);
1436
1437                 Inset & inset = cur.buffer().inset();
1438                 InsetIterator it  = inset_iterator_begin(inset);
1439                 InsetIterator const end = inset_iterator_end(inset);
1440                 for (; it != end; ++it) {
1441                         if (!it->asInsetMath()
1442                             && (inset_code == NO_CODE
1443                             || inset_code == it->lyxCode())) {
1444                                 Cursor tmpcur = cur;
1445                                 tmpcur.pushBackward(*it);
1446                                 it->dispatch(tmpcur, fr);
1447                         }
1448                 }
1449                 processUpdateFlags(Update::Force | Update::FitCursor);
1450                 break;
1451         }
1452
1453         default:
1454                 return false;
1455         }
1456
1457         return true;
1458 }
1459
1460
1461 docstring const BufferView::requestSelection()
1462 {
1463         Cursor & cur = d->cursor_;
1464
1465         if (!cur.selection()) {
1466                 d->xsel_cache_.set = false;
1467                 return docstring();
1468         }
1469
1470         if (!d->xsel_cache_.set ||
1471             cur.top() != d->xsel_cache_.cursor ||
1472             cur.anchor_.top() != d->xsel_cache_.anchor)
1473         {
1474                 d->xsel_cache_.cursor = cur.top();
1475                 d->xsel_cache_.anchor = cur.anchor_.top();
1476                 d->xsel_cache_.set = cur.selection();
1477                 return cur.selectionAsString(false);
1478         }
1479         return docstring();
1480 }
1481
1482
1483 void BufferView::clearSelection()
1484 {
1485         d->cursor_.clearSelection();
1486         // Clear the selection buffer. Otherwise a subsequent
1487         // middle-mouse-button paste would use the selection buffer,
1488         // not the more current external selection.
1489         cap::clearSelection();
1490         d->xsel_cache_.set = false;
1491         // The buffer did not really change, but this causes the
1492         // redraw we need because we cleared the selection above.
1493         buffer_.changed();
1494 }
1495
1496
1497 void BufferView::resize(int width, int height)
1498 {
1499         // Update from work area
1500         width_ = width;
1501         height_ = height;
1502
1503         // Clear the paragraph height cache.
1504         d->par_height_.clear();
1505         // Redo the metrics.
1506         updateMetrics();
1507 }
1508
1509
1510 Inset const * BufferView::getCoveringInset(Text const & text,
1511                 int x, int y) const
1512 {
1513         TextMetrics & tm = d->text_metrics_[&text];
1514         Inset * inset = tm.checkInsetHit(x, y);
1515         if (!inset)
1516                 return 0;
1517
1518         if (!inset->descendable())
1519                 // No need to go further down if the inset is not
1520                 // descendable.
1521                 return inset;
1522
1523         size_t cell_number = inset->nargs();
1524         // Check all the inner cell.
1525         for (size_t i = 0; i != cell_number; ++i) {
1526                 Text const * inner_text = inset->getText(i);
1527                 if (inner_text) {
1528                         // Try deeper.
1529                         Inset const * inset_deeper =
1530                                 getCoveringInset(*inner_text, x, y);
1531                         if (inset_deeper)
1532                                 return inset_deeper;
1533                 }
1534         }
1535
1536         return inset;
1537 }
1538
1539
1540 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1541 {
1542         //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
1543
1544         // This is only called for mouse related events including
1545         // LFUN_FILE_OPEN generated by drag-and-drop.
1546         FuncRequest cmd = cmd0;
1547
1548         Cursor old = cursor();
1549         Cursor cur(*this);
1550         cur.push(buffer_.inset());
1551         cur.selection() = d->cursor_.selection();
1552
1553         // Either the inset under the cursor or the
1554         // surrounding Text will handle this event.
1555
1556         // make sure we stay within the screen...
1557         cmd.y = min(max(cmd.y, -1), height_);
1558
1559         if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1560
1561                 // Get inset under mouse, if there is one.
1562                 Inset const * covering_inset =
1563                         getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1564                 if (covering_inset == d->last_inset_)
1565                         // Same inset, no need to do anything...
1566                         return;
1567
1568                 bool need_redraw = false;
1569                 // const_cast because of setMouseHover().
1570                 Inset * inset = const_cast<Inset *>(covering_inset);
1571                 if (d->last_inset_)
1572                         // Remove the hint on the last hovered inset (if any).
1573                         need_redraw |= d->last_inset_->setMouseHover(false);
1574                 if (inset)
1575                         // Highlighted the newly hovered inset (if any).
1576                         need_redraw |= inset->setMouseHover(true);
1577                 d->last_inset_ = inset;
1578                 if (!need_redraw)
1579                         return;
1580
1581                 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
1582                         << cmd.x << ", " << cmd.y << ")");
1583
1584                 d->update_strategy_ = DecorationUpdate;
1585
1586                 // This event (moving without mouse click) is not passed further.
1587                 // This should be changed if it is further utilized.
1588                 buffer_.changed();
1589                 return;
1590         }
1591
1592         // Build temporary cursor.
1593         Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1594
1595         // Put anchor at the same position.
1596         cur.resetAnchor();
1597
1598         // Try to dispatch to an non-editable inset near this position
1599         // via the temp cursor. If the inset wishes to change the real
1600         // cursor it has to do so explicitly by using
1601         //  cur.bv().cursor() = cur;  (or similar)
1602         if (inset)
1603                 inset->dispatch(cur, cmd);
1604
1605         // Now dispatch to the temporary cursor. If the real cursor should
1606         // be modified, the inset's dispatch has to do so explicitly.
1607         if (!inset || !cur.result().dispatched())
1608                 cur.dispatch(cmd);
1609
1610         // Notify left insets
1611         if (cur != old) {
1612                 old.fixIfBroken();
1613                 bool badcursor = notifyCursorLeaves(old, cur);
1614                 if (badcursor)
1615                         cursor().fixIfBroken();
1616         }
1617         
1618         // Do we have a selection?
1619         theSelection().haveSelection(cursor().selection());
1620
1621         // If the command has been dispatched,
1622         if (cur.result().dispatched() || cur.result().update())
1623                 processUpdateFlags(cur.result().update());
1624 }
1625
1626
1627 void BufferView::lfunScroll(FuncRequest const & cmd)
1628 {
1629         string const scroll_type = cmd.getArg(0);
1630         int const scroll_step = 
1631                 (scroll_type == "line") ? d->scrollbarParameters_.single_step
1632                 : (scroll_type == "page") ? d->scrollbarParameters_.page_step : 0;
1633         if (scroll_step == 0)
1634                 return;
1635         string const scroll_quantity = cmd.getArg(1);
1636         if (scroll_quantity == "up")
1637                 scrollUp(scroll_step);
1638         else if (scroll_quantity == "down")
1639                 scrollDown(scroll_step);
1640         else {
1641                 int const scroll_value = convert<int>(scroll_quantity);
1642                 if (scroll_value)
1643                         scroll(scroll_step * scroll_value);
1644         }
1645 }
1646
1647
1648 void BufferView::scroll(int y)
1649 {
1650         if (y > 0)
1651                 scrollDown(y);
1652         else if (y < 0)
1653                 scrollUp(-y);
1654 }
1655
1656
1657 void BufferView::scrollDown(int offset)
1658 {
1659         Text * text = &buffer_.text();
1660         TextMetrics & tm = d->text_metrics_[text];
1661         int ymax = height_ + offset;
1662         while (true) {
1663                 pair<pit_type, ParagraphMetrics const *> last = tm.last();
1664                 int bottom_pos = last.second->position() + last.second->descent();
1665                 if (last.first + 1 == int(text->paragraphs().size())) {
1666                         if (bottom_pos <= height_)
1667                                 return;
1668                         offset = min(offset, bottom_pos - height_);
1669                         break;
1670                 }
1671                 if (bottom_pos > ymax)
1672                         break;
1673                 tm.newParMetricsDown();
1674         }
1675         d->anchor_ypos_ -= offset;
1676         updateMetrics();
1677         buffer_.changed();
1678 }
1679
1680
1681 void BufferView::scrollUp(int offset)
1682 {
1683         Text * text = &buffer_.text();
1684         TextMetrics & tm = d->text_metrics_[text];
1685         int ymin = - offset;
1686         while (true) {
1687                 pair<pit_type, ParagraphMetrics const *> first = tm.first();
1688                 int top_pos = first.second->position() - first.second->ascent();
1689                 if (first.first == 0) {
1690                         if (top_pos >= 0)
1691                                 return;
1692                         offset = min(offset, - top_pos);
1693                         break;
1694                 }
1695                 if (top_pos < ymin)
1696                         break;
1697                 tm.newParMetricsUp();
1698         }
1699         d->anchor_ypos_ += offset;
1700         updateMetrics();
1701         buffer_.changed();
1702 }
1703
1704
1705 void BufferView::setCursorFromRow(int row)
1706 {
1707         int tmpid = -1;
1708         int tmppos = -1;
1709
1710         buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1711
1712         d->cursor_.reset(buffer_.inset());
1713         if (tmpid == -1)
1714                 buffer_.text().setCursor(d->cursor_, 0, 0);
1715         else
1716                 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1717 }
1718
1719
1720 void BufferView::gotoLabel(docstring const & label)
1721 {
1722         Toc & toc = buffer().tocBackend().toc("label");
1723         TocIterator toc_it = toc.begin();
1724         TocIterator end = toc.end();
1725         for (; toc_it != end; ++toc_it) {
1726                 if (label == toc_it->str())
1727                         dispatch(toc_it->action());
1728         }
1729         //FIXME: We could do a bit more searching thanks to this:
1730         //InsetLabel const * inset = buffer_.insetLabel(label);
1731 }
1732
1733
1734 TextMetrics const & BufferView::textMetrics(Text const * t) const
1735 {
1736         return const_cast<BufferView *>(this)->textMetrics(t);
1737 }
1738
1739
1740 TextMetrics & BufferView::textMetrics(Text const * t)
1741 {
1742         TextMetricsCache::iterator tmc_it  = d->text_metrics_.find(t);
1743         if (tmc_it == d->text_metrics_.end()) {
1744                 tmc_it = d->text_metrics_.insert(
1745                         make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1746         }
1747         return tmc_it->second;
1748 }
1749
1750
1751 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1752                 pit_type pit) const
1753 {
1754         return textMetrics(t).parMetrics(pit);
1755 }
1756
1757
1758 int BufferView::workHeight() const
1759 {
1760         return height_;
1761 }
1762
1763
1764 void BufferView::setCursor(DocIterator const & dit)
1765 {
1766         size_t const n = dit.depth();
1767         for (size_t i = 0; i < n; ++i)
1768                 dit[i].inset().edit(d->cursor_, true);
1769
1770         d->cursor_.setCursor(dit);
1771         d->cursor_.selection() = false;
1772 }
1773
1774
1775 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1776 {
1777         // Would be wrong to delete anything if we have a selection.
1778         if (cur.selection())
1779                 return false;
1780
1781         bool need_anchor_change = false;
1782         bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1783                 need_anchor_change);
1784
1785         if (need_anchor_change)
1786                 cur.resetAnchor();
1787
1788         if (!changed)
1789                 return false;
1790
1791         d->cursor_ = cur;
1792
1793         updateLabels(buffer_);
1794
1795         updateMetrics();
1796         buffer_.changed();
1797         return true;
1798 }
1799
1800
1801 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
1802 {
1803         LASSERT(&cur.bv() == this, /**/);
1804
1805         if (!select)
1806                 // this event will clear selection so we save selection for
1807                 // persistent selection
1808                 cap::saveSelection(cursor());
1809
1810         // Has the cursor just left the inset?
1811         bool badcursor = false;
1812         bool leftinset = (&d->cursor_.inset() != &cur.inset());
1813         if (leftinset) {
1814                 d->cursor_.fixIfBroken();
1815                 badcursor = notifyCursorLeaves(d->cursor_, cur);
1816                 if (badcursor)
1817                         cur.fixIfBroken();
1818         }
1819
1820         // FIXME: shift-mouse selection doesn't work well across insets.
1821         bool do_selection = select && &d->cursor_.anchor().inset() == &cur.inset();
1822
1823         // do the dEPM magic if needed
1824         // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1825         // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1826         // the leftinset bool would not be necessary (badcursor instead).
1827         bool update = leftinset;
1828         if (!do_selection && !badcursor && d->cursor_.inTexted())
1829                 update |= checkDepm(cur, d->cursor_);
1830
1831         d->cursor_.setCursor(cur);
1832         d->cursor_.boundary(cur.boundary());
1833         if (do_selection)
1834                 d->cursor_.setSelection();
1835         else
1836                 d->cursor_.clearSelection();
1837
1838         d->cursor_.finishUndo();
1839         d->cursor_.setCurrentFont();
1840         return update;
1841 }
1842
1843
1844 void BufferView::putSelectionAt(DocIterator const & cur,
1845                                 int length, bool backwards)
1846 {
1847         d->cursor_.clearSelection();
1848
1849         setCursor(cur);
1850
1851         if (length) {
1852                 if (backwards) {
1853                         d->cursor_.pos() += length;
1854                         d->cursor_.setSelection(d->cursor_, -length);
1855                 } else
1856                         d->cursor_.setSelection(d->cursor_, length);
1857         }
1858         // Ensure a redraw happens in any case because the new selection could 
1859         // possibly be on the same screen as the previous selection.
1860         processUpdateFlags(Update::Force | Update::FitCursor);
1861 }
1862
1863
1864 Cursor & BufferView::cursor()
1865 {
1866         return d->cursor_;
1867 }
1868
1869
1870 Cursor const & BufferView::cursor() const
1871 {
1872         return d->cursor_;
1873 }
1874
1875
1876 pit_type BufferView::anchor_ref() const
1877 {
1878         return d->anchor_pit_;
1879 }
1880
1881
1882 bool BufferView::singleParUpdate()
1883 {
1884         Text & buftext = buffer_.text();
1885         pit_type const bottom_pit = d->cursor_.bottom().pit();
1886         TextMetrics & tm = textMetrics(&buftext);
1887         int old_height = tm.parMetrics(bottom_pit).height();
1888
1889         // make sure inline completion pointer is ok
1890         if (d->inlineCompletionPos_.fixIfBroken())
1891                 d->inlineCompletionPos_ = DocIterator();
1892
1893         // In Single Paragraph mode, rebreak only
1894         // the (main text, not inset!) paragraph containing the cursor.
1895         // (if this paragraph contains insets etc., rebreaking will
1896         // recursively descend)
1897         tm.redoParagraph(bottom_pit);
1898         ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);                
1899         if (pm.height() != old_height)
1900                 // Paragraph height has changed so we cannot proceed to
1901                 // the singlePar optimisation.
1902                 return false;
1903
1904         d->update_strategy_ = SingleParUpdate;
1905
1906         LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
1907                 << " y2: " << pm.position() + pm.descent()
1908                 << " pit: " << bottom_pit
1909                 << " singlepar: 1");
1910         return true;
1911 }
1912
1913
1914 void BufferView::updateMetrics()
1915 {
1916         if (height_ == 0 || width_ == 0)
1917                 return;
1918
1919         Text & buftext = buffer_.text();
1920         pit_type const npit = int(buftext.paragraphs().size());
1921
1922         // Clear out the position cache in case of full screen redraw,
1923         d->coord_cache_.clear();
1924
1925         // Clear out paragraph metrics to avoid having invalid metrics
1926         // in the cache from paragraphs not relayouted below
1927         // The complete text metrics will be redone.
1928         d->text_metrics_.clear();
1929
1930         TextMetrics & tm = textMetrics(&buftext);
1931
1932         // make sure inline completion pointer is ok
1933         if (d->inlineCompletionPos_.fixIfBroken())
1934                 d->inlineCompletionPos_ = DocIterator();
1935         
1936         if (d->anchor_pit_ >= npit)
1937                 // The anchor pit must have been deleted...
1938                 d->anchor_pit_ = npit - 1;
1939
1940         // Rebreak anchor paragraph.
1941         tm.redoParagraph(d->anchor_pit_);
1942         ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
1943         
1944         // position anchor
1945         if (d->anchor_pit_ == 0) {
1946                 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
1947                 
1948                 // Complete buffer visible? Then it's easy.
1949                 if (scrollRange == 0)
1950                         d->anchor_ypos_ = anchor_pm.ascent();
1951         
1952                 // FIXME: Some clever handling needed to show
1953                 // the _first_ paragraph up to the top if the cursor is
1954                 // in the first line.
1955         }               
1956         anchor_pm.setPosition(d->anchor_ypos_);
1957
1958         LYXERR(Debug::PAINTING, "metrics: "
1959                 << " anchor pit = " << d->anchor_pit_
1960                 << " anchor ypos = " << d->anchor_ypos_);
1961
1962         // Redo paragraphs above anchor if necessary.
1963         int y1 = d->anchor_ypos_ - anchor_pm.ascent();
1964         // We are now just above the anchor paragraph.
1965         pit_type pit1 = d->anchor_pit_ - 1;
1966         for (; pit1 >= 0 && y1 >= 0; --pit1) {
1967                 tm.redoParagraph(pit1);
1968                 ParagraphMetrics & pm = tm.par_metrics_[pit1];
1969                 y1 -= pm.descent();
1970                 // Save the paragraph position in the cache.
1971                 pm.setPosition(y1);
1972                 y1 -= pm.ascent();
1973         }
1974
1975         // Redo paragraphs below the anchor if necessary.
1976         int y2 = d->anchor_ypos_ + anchor_pm.descent();
1977         // We are now just below the anchor paragraph.
1978         pit_type pit2 = d->anchor_pit_ + 1;
1979         for (; pit2 < npit && y2 <= height_; ++pit2) {
1980                 tm.redoParagraph(pit2);
1981                 ParagraphMetrics & pm = tm.par_metrics_[pit2];
1982                 y2 += pm.ascent();
1983                 // Save the paragraph position in the cache.
1984                 pm.setPosition(y2);
1985                 y2 += pm.descent();
1986         }
1987
1988         LYXERR(Debug::PAINTING, "Metrics: "
1989                 << " anchor pit = " << d->anchor_pit_
1990                 << " anchor ypos = " << d->anchor_ypos_
1991                 << " y1 = " << y1
1992                 << " y2 = " << y2
1993                 << " pit1 = " << pit1
1994                 << " pit2 = " << pit2);
1995
1996         d->update_strategy_ = FullScreenUpdate;
1997
1998         if (lyxerr.debugging(Debug::WORKAREA)) {
1999                 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
2000                 d->coord_cache_.dump();
2001         }
2002 }
2003
2004
2005 void BufferView::insertLyXFile(FileName const & fname)
2006 {
2007         LASSERT(d->cursor_.inTexted(), /**/);
2008
2009         // Get absolute path of file and add ".lyx"
2010         // to the filename if necessary
2011         FileName filename = fileSearch(string(), fname.absFilename(), "lyx");
2012
2013         docstring const disp_fn = makeDisplayPath(filename.absFilename());
2014         // emit message signal.
2015         message(bformat(_("Inserting document %1$s..."), disp_fn));
2016
2017         docstring res;
2018         Buffer buf("", false);
2019         if (buf.loadLyXFile(filename)) {
2020                 ErrorList & el = buffer_.errorList("Parse");
2021                 // Copy the inserted document error list into the current buffer one.
2022                 el = buf.errorList("Parse");
2023                 buffer_.undo().recordUndo(d->cursor_);
2024                 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
2025                                              buf.params().documentClassPtr(), el);
2026                 res = _("Document %1$s inserted.");
2027         } else {
2028                 res = _("Could not insert document %1$s");
2029         }
2030
2031         updateMetrics();
2032         buffer_.changed();
2033         // emit message signal.
2034         message(bformat(res, disp_fn));
2035         buffer_.errors("Parse");
2036 }
2037
2038
2039 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
2040 {
2041         int x = 0;
2042         int y = 0;
2043         int lastw = 0;
2044
2045         // Addup contribution of nested insets, from inside to outside,
2046         // keeping the outer paragraph for a special handling below
2047         for (size_t i = dit.depth() - 1; i >= 1; --i) {
2048                 CursorSlice const & sl = dit[i];
2049                 int xx = 0;
2050                 int yy = 0;
2051                 
2052                 // get relative position inside sl.inset()
2053                 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
2054                 
2055                 // Make relative position inside of the edited inset relative to sl.inset()
2056                 x += xx;
2057                 y += yy;
2058                 
2059                 // In case of an RTL inset, the edited inset will be positioned to the left
2060                 // of xx:yy
2061                 if (sl.text()) {
2062                         bool boundary_i = boundary && i + 1 == dit.depth();
2063                         bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
2064                         if (rtl)
2065                                 x -= lastw;
2066                 }
2067
2068                 // remember width for the case that sl.inset() is positioned in an RTL inset
2069                 if (i && dit[i - 1].text()) {
2070                         // If this Inset is inside a Text Inset, retrieve the Dimension
2071                         // from the containing text instead of using Inset::dimension() which
2072                         // might not be implemented.
2073                         // FIXME (Abdel 23/09/2007): this is a bit messy because of the
2074                         // elimination of Inset::dim_ cache. This coordOffset() method needs
2075                         // to be rewritten in light of the new design.
2076                         Dimension const & dim = parMetrics(dit[i - 1].text(),
2077                                 dit[i - 1].pit()).insetDimension(&sl.inset());
2078                         lastw = dim.wid;
2079                 } else {
2080                         Dimension const dim = sl.inset().dimension(*this);
2081                         lastw = dim.wid;
2082                 }
2083                 
2084                 //lyxerr << "Cursor::getPos, i: "
2085                 // << i << " x: " << xx << " y: " << y << endl;
2086         }
2087
2088         // Add contribution of initial rows of outermost paragraph
2089         CursorSlice const & sl = dit[0];
2090         TextMetrics const & tm = textMetrics(sl.text());
2091         ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
2092         LASSERT(!pm.rows().empty(), /**/);
2093         y -= pm.rows()[0].ascent();
2094 #if 1
2095         // FIXME: document this mess
2096         size_t rend;
2097         if (sl.pos() > 0 && dit.depth() == 1) {
2098                 int pos = sl.pos();
2099                 if (pos && boundary)
2100                         --pos;
2101 //              lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
2102                 rend = pm.pos2row(pos);
2103         } else
2104                 rend = pm.pos2row(sl.pos());
2105 #else
2106         size_t rend = pm.pos2row(sl.pos());
2107 #endif
2108         for (size_t rit = 0; rit != rend; ++rit)
2109                 y += pm.rows()[rit].height();
2110         y += pm.rows()[rend].ascent();
2111         
2112         TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
2113         
2114         // Make relative position from the nested inset now bufferview absolute.
2115         int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
2116         x += xx;
2117         
2118         // In the RTL case place the nested inset at the left of the cursor in 
2119         // the outer paragraph
2120         bool boundary_1 = boundary && 1 == dit.depth();
2121         bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
2122         if (rtl)
2123                 x -= lastw;
2124         
2125         return Point(x, y);
2126 }
2127
2128
2129 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
2130 {
2131         CursorSlice const & bot = dit.bottom();
2132         TextMetrics const & tm = textMetrics(bot.text());
2133         if (!tm.contains(bot.pit()))
2134                 return Point(-1, -1);
2135
2136         Point p = coordOffset(dit, boundary); // offset from outer paragraph
2137         p.y_ += tm.parMetrics(bot.pit()).position();
2138         return p;
2139 }
2140
2141
2142 void BufferView::draw(frontend::Painter & pain)
2143 {
2144         if (height_ == 0 || width_ == 0)
2145                 return;
2146         LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
2147         Text & text = buffer_.text();
2148         TextMetrics const & tm = d->text_metrics_[&text];
2149         int const y = tm.first().second->position();
2150         PainterInfo pi(this, pain);
2151
2152         switch (d->update_strategy_) {
2153
2154         case NoScreenUpdate:
2155                 // If no screen painting is actually needed, only some the different
2156                 // coordinates of insets and paragraphs needs to be updated.
2157                 pi.full_repaint = true;
2158                 pi.pain.setDrawingEnabled(false);
2159                 tm.draw(pi, 0, y);
2160                 break;
2161
2162         case SingleParUpdate:
2163                 pi.full_repaint = false;
2164                 // In general, only the current row of the outermost paragraph
2165                 // will be redrawn. Particular cases where selection spans
2166                 // multiple paragraph are correctly detected in TextMetrics.
2167                 tm.draw(pi, 0, y);
2168                 break;
2169
2170         case DecorationUpdate:
2171                 // FIXME: We should also distinguish DecorationUpdate to avoid text
2172                 // drawing if possible. This is not possible to do easily right now
2173                 // because of the single backing pixmap.
2174
2175         case FullScreenUpdate:
2176                 // The whole screen, including insets, will be refreshed.
2177                 pi.full_repaint = true;
2178
2179                 // Clear background.
2180                 pain.fillRectangle(0, 0, width_, height_,
2181                         buffer_.inset().backgroundColor());
2182
2183                 // Draw everything.
2184                 tm.draw(pi, 0, y);
2185
2186                 // and possibly grey out below
2187                 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2188                 int const y2 = lastpm.second->position() + lastpm.second->descent();
2189                 if (y2 < height_)
2190                         pain.fillRectangle(0, y2, width_, height_ - y2, Color_bottomarea);
2191                 break;
2192         }
2193         LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING  ***");
2194
2195         // The scrollbar needs an update.
2196         updateScrollbar();
2197
2198         // Normalize anchor for next time
2199         pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
2200         pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2201         for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
2202                 ParagraphMetrics const & pm = tm.parMetrics(pit);
2203                 if (pm.position() + pm.descent() > 0) {
2204                         d->anchor_pit_ = pit;
2205                         d->anchor_ypos_ = pm.position();
2206                         break;
2207                 }
2208         }
2209         LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
2210                 << "  anchor ypos = " << d->anchor_ypos_);
2211 }
2212
2213
2214 void BufferView::message(docstring const & msg)
2215 {
2216         if (d->gui_)
2217                 d->gui_->message(msg);
2218 }
2219
2220
2221 void BufferView::showDialog(string const & name)
2222 {
2223         if (d->gui_)
2224                 d->gui_->showDialog(name, string());
2225 }
2226
2227
2228 void BufferView::showDialog(string const & name,
2229         string const & data, Inset * inset)
2230 {
2231         if (d->gui_)
2232                 d->gui_->showDialog(name, data, inset);
2233 }
2234
2235
2236 void BufferView::updateDialog(string const & name, string const & data)
2237 {
2238         if (d->gui_)
2239                 d->gui_->updateDialog(name, data);
2240 }
2241
2242
2243 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2244 {
2245         d->gui_ = gui;
2246 }
2247
2248
2249 // FIXME: Move this out of BufferView again
2250 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
2251 {
2252         if (!fname.isReadableFile()) {
2253                 docstring const error = from_ascii(strerror(errno));
2254                 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2255                 docstring const text =
2256                   bformat(_("Could not read the specified document\n"
2257                             "%1$s\ndue to the error: %2$s"), file, error);
2258                 Alert::error(_("Could not read file"), text);
2259                 return docstring();
2260         }
2261
2262         if (!fname.isReadableFile()) {
2263                 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2264                 docstring const text =
2265                   bformat(_("%1$s\n is not readable."), file);
2266                 Alert::error(_("Could not open file"), text);
2267                 return docstring();
2268         }
2269
2270         // FIXME UNICODE: We don't know the encoding of the file
2271         docstring file_content = fname.fileContents("UTF-8");
2272         if (file_content.empty()) {
2273                 Alert::error(_("Reading not UTF-8 encoded file"),
2274                              _("The file is not UTF-8 encoded.\n"
2275                                "It will be read as local 8Bit-encoded.\n"
2276                                "If this does not give the correct result\n"
2277                                "then please change the encoding of the file\n"
2278                                "to UTF-8 with a program other than LyX.\n"));
2279                 file_content = fname.fileContents("local8bit");
2280         }
2281
2282         return normalize_c(file_content);
2283 }
2284
2285
2286 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
2287 {
2288         docstring const tmpstr = contentsOfPlaintextFile(f);
2289
2290         if (tmpstr.empty())
2291                 return;
2292
2293         Cursor & cur = cursor();
2294         cap::replaceSelection(cur);
2295         buffer_.undo().recordUndo(cur);
2296         if (asParagraph)
2297                 cur.innerText()->insertStringAsParagraphs(cur, tmpstr);
2298         else
2299                 cur.innerText()->insertStringAsLines(cur, tmpstr);
2300
2301         updateMetrics();
2302         buffer_.changed();
2303 }
2304
2305
2306 docstring const & BufferView::inlineCompletion() const
2307 {
2308         return d->inlineCompletion_;
2309 }
2310
2311
2312 size_t const & BufferView::inlineCompletionUniqueChars() const
2313 {
2314         return d->inlineCompletionUniqueChars_;
2315 }
2316
2317
2318 DocIterator const & BufferView::inlineCompletionPos() const
2319 {
2320         return d->inlineCompletionPos_;
2321 }
2322
2323
2324 bool samePar(DocIterator const & a, DocIterator const & b)
2325 {
2326         if (a.empty() && b.empty())
2327                 return true;
2328         if (a.empty() || b.empty())
2329                 return false;
2330         return &a.innerParagraph() == &b.innerParagraph();
2331 }
2332
2333
2334 void BufferView::setInlineCompletion(Cursor & cur, DocIterator const & pos, 
2335         docstring const & completion, size_t uniqueChars)
2336 {
2337         uniqueChars = min(completion.size(), uniqueChars);
2338         bool changed = d->inlineCompletion_ != completion
2339                 || d->inlineCompletionUniqueChars_ != uniqueChars;
2340         bool singlePar = true;
2341         d->inlineCompletion_ = completion;
2342         d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
2343         
2344         //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
2345         
2346         // at new position?
2347         DocIterator const & old = d->inlineCompletionPos_;
2348         if (old != pos) {
2349                 //lyxerr << "inlineCompletionPos changed" << std::endl;
2350                 // old or pos are in another paragraph?
2351                 if ((!samePar(cur, pos) && !pos.empty())
2352                     || (!samePar(cur, old) && !old.empty())) {
2353                         singlePar = false;
2354                         //lyxerr << "different paragraph" << std::endl;
2355                 }
2356                 d->inlineCompletionPos_ = pos;
2357         }
2358         
2359         // set update flags
2360         if (changed) {
2361                 if (singlePar && !(cur.disp_.update() & Update::Force))
2362                         cur.updateFlags(cur.disp_.update() | Update::SinglePar);
2363                 else
2364                         cur.updateFlags(cur.disp_.update() | Update::Force);
2365         }
2366 }
2367
2368 } // namespace lyx