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