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