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