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