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