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