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