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