3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Alfredo Braunstein
7 * \author Lars Gullik Bjønnes
10 * \author Jürgen Vigna
12 * Full author contact details are available in file CREDITS.
17 #include "BufferView.h"
20 #include "buffer_funcs.h"
21 #include "bufferlist.h"
22 #include "bufferparams.h"
23 #include "coordcache.h"
24 #include "CutAndPaste.h"
26 #include "dispatchresult.h"
27 #include "errorlist.h"
29 #include "FloatList.h"
30 #include "funcrequest.h"
31 #include "FuncStatus.h"
34 #include "insetiterator.h"
36 #include "LaTeXFeatures.h"
37 #include "lyx_cb.h" // added for Dispatch functions
41 #include "lyxlayout.h"
43 #include "lyxtextclass.h"
46 #include "paragraph.h"
47 #include "paragraph_funcs.h"
48 #include "ParagraphParameters.h"
49 #include "pariterator.h"
54 #include "WordLangTuple.h"
55 #include "metricsinfo.h"
57 #include "insets/insetbibtex.h"
58 #include "insets/insetcommand.h" // ChangeRefs
59 #include "insets/insetref.h"
60 #include "insets/insettext.h"
62 #include "frontends/Alert.h"
63 #include "frontends/FileDialog.h"
64 #include "frontends/FontMetrics.h"
66 #include "graphics/Previews.h"
68 #include "support/convert.h"
69 #include "support/filefilterlist.h"
70 #include "support/filetools.h"
71 #include "support/package.h"
72 #include "support/types.h"
74 #include <boost/bind.hpp>
75 #include <boost/current_function.hpp>
83 using support::addPath;
84 using support::bformat;
85 using support::FileFilterList;
86 using support::fileSearch;
87 using support::isDirWriteable;
88 using support::makeDisplayPath;
89 using support::makeAbsPath;
90 using support::package;
94 using std::istringstream;
98 using std::mem_fun_ref;
102 namespace Alert = frontend::Alert;
106 /// Return an inset of this class if it exists at the current cursor position
108 T * getInsetByCode(LCursor & cur, InsetBase::Code code)
111 DocIterator it = cur;
112 if (it.nextInset() &&
113 it.nextInset()->lyxCode() == code) {
114 inset = static_cast<T*>(it.nextInset());
122 BufferView::BufferView()
123 : width_(0), height_(0), buffer_(0), wh_(0),
125 multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
128 xsel_cache_.set = false;
129 intl_->initKeyMapper(lyxrc.use_kbmap);
133 BufferView::~BufferView()
138 Buffer * BufferView::buffer() const
144 void BufferView::setBuffer(Buffer * b)
146 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
147 << "[ b = " << b << "]" << endl;
150 // Save the actual cursor position and anchor inside the
151 // buffer so that it can be restored in case we rechange
152 // to this buffer later on.
153 buffer_->saveCursor(cursor_.selectionBegin(),
154 cursor_.selectionEnd());
155 // current buffer is going to be switched-off, save cursor pos
156 LyX::ref().session().lastFilePos().save(buffer_->fileName(),
157 boost::tie(cursor_.pit(), cursor_.pos()) );
160 // If we're quitting lyx, don't bother updating stuff
166 // If we are closing current buffer, switch to the first in
169 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
170 << " No Buffer!" << endl;
171 // We are closing the buffer, use the first buffer as current
172 buffer_ = theBufferList().first();
174 // Set current buffer
179 cursor_ = LCursor(*this);
184 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
185 << "Buffer addr: " << buffer_ << endl;
186 cursor_.push(buffer_->inset());
187 cursor_.resetAnchor();
188 buffer_->text().init(this);
189 buffer_->text().setCurrentFont(cursor_);
190 if (buffer_->getCursor().size() > 0 &&
191 buffer_->getAnchor().size() > 0)
193 cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
194 cursor_.resetAnchor();
195 cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
196 cursor_.setSelection();
200 updateMetrics(false);
202 if (buffer_ && graphics::Previews::status() != LyXRC::PREVIEW_OFF)
203 graphics::Previews::get().generateBufferPreviews(*buffer_);
207 bool BufferView::loadLyXFile(string const & filename, bool tolastfiles)
209 // Get absolute path of file and add ".lyx"
210 // to the filename if necessary
211 string s = fileSearch(string(), filename, "lyx");
213 bool const found = !s.empty();
218 // File already open?
219 if (theBufferList().exists(s)) {
220 docstring const file = makeDisplayPath(s, 20);
221 docstring text = bformat(_("The document %1$s is already "
222 "loaded.\n\nDo you want to revert "
223 "to the saved version?"), file);
224 int const ret = Alert::prompt(_("Revert to saved document?"),
225 text, 0, 1, _("&Revert"), _("&Switch to document"));
228 setBuffer(theBufferList().getBuffer(s));
231 // FIXME: should be LFUN_REVERT
232 if (!theBufferList().close(theBufferList().getBuffer(s), false))
234 // Fall through to new load. (Asger)
241 b = theBufferList().newBuffer(s);
242 if (!lyx::loadLyXFile(b, s)) {
243 theBufferList().release(b);
247 docstring text = bformat(_("The document %1$s does not yet "
248 "exist.\n\nDo you want to create "
249 "a new document?"), from_utf8(s));
250 int const ret = Alert::prompt(_("Create new document?"),
251 text, 0, 1, _("&Create"), _("Cancel"));
254 b = newFile(s, string(), true);
262 // Send the "errors" signal in case of parsing errors
265 // scroll to the position when the file was last closed
266 if (lyxrc.use_lastfilepos) {
269 boost::tie(pit, pos) = LyX::ref().session().lastFilePos().load(s);
270 // I am not sure how to separate the following part to a function
271 // so I will leave this to Lars.
273 // check pit since the document may be externally changed.
274 if ( static_cast<size_t>(pit) < b->paragraphs().size() ) {
275 ParIterator it = b->par_iterator_begin();
276 ParIterator const end = b->par_iterator_end();
277 for (; it != end; ++it)
278 if (it.pit() == pit) {
279 // restored pos may be bigger than it->size
280 setCursor(makeDocIterator(it, min(pos, it->size())));
281 update(Update::FitCursor);
288 LyX::ref().session().lastFiles().add(b->fileName());
294 void BufferView::reload()
296 string const fn = buffer_->fileName();
297 if (theBufferList().close(buffer_, false))
302 void BufferView::resize()
307 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
309 buffer_->text().init(this);
315 bool BufferView::fitCursor()
317 if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
318 frontend::FontMetrics const & fm =
319 theFontMetrics(cursor_.getFont());
320 int const asc = fm.maxAscent();
321 int const des = fm.maxDescent();
322 Point const p = bv_funcs::getPos(*this, cursor_, cursor_.boundary());
323 if (p.y_ - asc >= 0 && p.y_ + des < height_)
331 bool BufferView::multiParSel()
333 if (!cursor_.selection())
335 bool ret = multiparsel_cache_;
336 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
337 // Either this, or previous selection spans paragraphs
338 return ret || multiparsel_cache_;
342 std::pair<bool, bool> BufferView::update(Update::flags flags)
344 // This is close to a hot-path.
345 if (lyxerr.debugging(Debug::DEBUG)) {
347 << BOOST_CURRENT_FUNCTION
348 << "[fitcursor = " << (flags & Update::FitCursor)
349 << ", forceupdate = " << (flags & Update::Force)
350 << ", singlepar = " << (flags & Update::SinglePar)
351 << "] buffer: " << buffer_ << endl;
354 // Check needed to survive LyX startup
356 return make_pair(false, false);
358 if (lyxerr.debugging(Debug::WORKAREA)) {
359 lyxerr[Debug::WORKAREA] << "BufferView::update" << std::endl;
362 // Update macro store
363 buffer_->buildMacros();
365 // Now do the first drawing step if needed. This consists on updating
366 // the CoordCache in updateMetrics().
367 // The second drawing step is done in WorkArea::redraw() if needed.
369 // Case when no explicit update is requested.
371 // no need to do anything.
372 return make_pair(false, false);
375 bool full_metrics = flags & Update::Force;
376 if (flags & Update::MultiParSel)
377 full_metrics |= multiParSel();
379 bool const single_par = !full_metrics;
380 updateMetrics(single_par);
382 if (flags & Update::FitCursor && fitCursor())
383 updateMetrics(false);
385 // tell the frontend to update the screen.
386 return make_pair(true, single_par);
390 void BufferView::updateScrollbar()
393 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
394 << " no text in updateScrollbar" << endl;
395 scrollbarParameters_.reset();
399 LyXText & t = buffer_->text();
400 int const parsize = int(t.paragraphs().size() - 1);
401 if (anchor_ref_ > parsize) {
402 anchor_ref_ = parsize;
406 if (lyxerr.debugging(Debug::GUI)) {
408 << BOOST_CURRENT_FUNCTION
409 << " Updating scrollbar: height: " << t.paragraphs().size()
410 << " curr par: " << cursor_.bottom().pit()
411 << " default height " << defaultRowHeight() << endl;
414 // It would be better to fix the scrollbar to understand
415 // values in [0..1] and divide everything by wh
417 // estimated average paragraph height:
420 int h = t.getPar(anchor_ref_).height();
422 // Normalize anchor/offset (MV):
423 while (offset_ref_ > h && anchor_ref_ < parsize) {
426 h = t.getPar(anchor_ref_).height();
428 // Look at paragraph heights on-screen
431 for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
434 int const h2 = t.getPar(pit).height();
440 int const hav = sumh / nh;
441 // More realistic average paragraph height
446 scrollbarParameters_.height = (parsize + 1) * wh_;
447 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
448 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
452 ScrollbarParameters const & BufferView::scrollbarParameters() const
454 return scrollbarParameters_;
458 void BufferView::scrollDocView(int value)
460 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
461 << "[ value = " << value << "]" << endl;
466 LyXText & t = buffer_->text();
468 float const bar = value / float(wh_ * t.paragraphs().size());
470 anchor_ref_ = int(bar * t.paragraphs().size());
471 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
472 anchor_ref_ = int(t.paragraphs().size()) - 1;
473 t.redoParagraph(*this, anchor_ref_);
474 int const h = t.getPar(anchor_ref_).height();
475 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
476 updateMetrics(false);
480 void BufferView::setCursorFromScrollbar()
482 LyXText & t = buffer_->text();
484 int const height = 2 * defaultRowHeight();
485 int const first = height;
486 int const last = height_ - height;
487 LCursor & cur = cursor_;
489 bv_funcs::CurStatus st = bv_funcs::status(this, cur);
492 case bv_funcs::CUR_ABOVE:
493 t.setCursorFromCoordinates(cur, 0, first);
494 cur.clearSelection();
496 case bv_funcs::CUR_BELOW:
497 t.setCursorFromCoordinates(cur, 0, last);
498 cur.clearSelection();
500 case bv_funcs::CUR_INSIDE:
501 int const y = bv_funcs::getPos(*this, cur, cur.boundary()).y_;
502 int const newy = min(last, max(y, first));
504 cur.reset(buffer_->inset());
505 t.setCursorFromCoordinates(cur, 0, newy);
511 Change const BufferView::getCurrentChange() const
513 if (!cursor_.selection())
514 return Change(Change::UNCHANGED);
516 DocIterator dit = cursor_.selectionBegin();
517 return dit.paragraph().lookupChange(dit.pos());
521 void BufferView::saveBookmark(bool persistent)
523 LyX::ref().session().bookmarks().save(
525 cursor_.paragraph().id(),
530 // emit message signal.
531 message(_("Save bookmark"));
535 void BufferView::moveToPosition(int par_id, pos_type par_pos)
537 cursor_.clearSelection();
539 ParIterator par = buffer_->getParFromID(par_id);
540 if (par == buffer_->par_iterator_end())
543 setCursor(makeDocIterator(par, min(par->size(), par_pos)));
547 void BufferView::switchKeyMap()
549 if (!lyxrc.rtl_support)
552 if (getLyXText()->real_current_font.isRightToLeft()) {
553 if (intl_->keymap == Intl::PRIMARY)
556 if (intl_->keymap == Intl::SECONDARY)
562 int BufferView::workWidth() const
568 void BufferView::center()
570 CursorSlice & bot = cursor_.bottom();
571 pit_type const pit = bot.pit();
572 bot.text()->redoParagraph(*this, pit);
573 Paragraph const & par = bot.text()->paragraphs()[pit];
575 offset_ref_ = bv_funcs::coordOffset(*this, cursor_, cursor_.boundary()).y_
576 + par.ascent() - height_ / 2;
580 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
584 switch (cmd.action) {
587 flag.enabled(!buffer_->undostack().empty());
590 flag.enabled(!buffer_->redostack().empty());
592 case LFUN_FILE_INSERT:
593 case LFUN_FILE_INSERT_ASCII_PARA:
594 case LFUN_FILE_INSERT_ASCII:
595 case LFUN_BOOKMARK_SAVE:
596 // FIXME: Actually, these LFUNS should be moved to LyXText
597 flag.enabled(cursor_.inTexted());
599 case LFUN_FONT_STATE:
600 case LFUN_LABEL_INSERT:
601 case LFUN_PARAGRAPH_GOTO:
602 // FIXME handle non-trivially
603 case LFUN_OUTLINE_UP:
604 case LFUN_OUTLINE_DOWN:
605 case LFUN_OUTLINE_IN:
606 case LFUN_OUTLINE_OUT:
608 case LFUN_REFERENCE_NEXT:
610 case LFUN_WORD_REPLACE:
613 case LFUN_MARK_TOGGLE:
614 case LFUN_SCREEN_RECENTER:
615 case LFUN_BIBTEX_DATABASE_ADD:
616 case LFUN_BIBTEX_DATABASE_DEL:
617 case LFUN_WORDS_COUNT:
618 case LFUN_NEXT_INSET_TOGGLE:
622 case LFUN_LABEL_GOTO: {
623 flag.enabled(!cmd.argument().empty()
624 || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
628 case LFUN_CHANGES_TRACK:
630 flag.setOnOff(buffer_->params().trackChanges);
633 case LFUN_CHANGES_OUTPUT: {
634 OutputParams runparams;
635 LaTeXFeatures features(*buffer_, buffer_->params(), runparams);
636 flag.enabled(buffer_ && features.isAvailable("dvipost"));
637 flag.setOnOff(buffer_->params().outputChanges);
641 case LFUN_CHANGES_MERGE:
642 case LFUN_CHANGE_NEXT:
643 case LFUN_ALL_CHANGES_ACCEPT:
644 case LFUN_ALL_CHANGES_REJECT:
645 flag.enabled(buffer_); // FIXME: Change tracking (MG)
648 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
649 flag.setOnOff(buffer_->params().compressed);
661 bool BufferView::dispatch(FuncRequest const & cmd)
663 //lyxerr << BOOST_CURRENT_FUNCTION
664 // << [ cmd = " << cmd << "]" << endl;
666 // Make sure that the cached BufferView is correct.
667 lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
668 << " action[" << cmd.action << ']'
669 << " arg[" << to_utf8(cmd.argument()) << ']'
670 << " x[" << cmd.x << ']'
671 << " y[" << cmd.y << ']'
672 << " button[" << cmd.button() << ']'
675 LCursor & cur = cursor_;
677 switch (cmd.action) {
681 cur.message(_("Undo"));
682 cur.clearSelection();
683 if (!textUndo(*this))
684 cur.message(_("No further undo information"));
692 cur.message(_("Redo"));
693 cur.clearSelection();
694 if (!textRedo(*this))
695 cur.message(_("No further redo information"));
701 case LFUN_FILE_INSERT:
702 // FIXME: We don't know the encoding of filenames
703 menuInsertLyXFile(to_utf8(cmd.argument()));
706 case LFUN_FILE_INSERT_ASCII_PARA:
707 // FIXME: We don't know the encoding of filenames
708 insertAsciiFile(this, to_utf8(cmd.argument()), true);
711 case LFUN_FILE_INSERT_ASCII:
712 // FIXME: We don't know the encoding of filenames
713 insertAsciiFile(this, to_utf8(cmd.argument()), false);
716 case LFUN_FONT_STATE:
717 cur.message(from_utf8(cur.currentState()));
720 case LFUN_BOOKMARK_SAVE:
721 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
724 case LFUN_LABEL_GOTO: {
725 docstring label = cmd.argument();
728 getInsetByCode<InsetRef>(cursor_,
729 InsetBase::REF_CODE);
731 label = inset->getParam("reference");
732 // persistent=false: use temp_bookmark
742 case LFUN_PARAGRAPH_GOTO: {
743 int const id = convert<int>(to_utf8(cmd.argument()));
745 for (Buffer * b = buffer_; i == 0 || b != buffer_; b = theBufferList().next(b)) {
746 ParIterator par = b->getParFromID(id);
747 if (par == b->par_iterator_end()) {
749 << "No matching paragraph found! ["
750 << id << "]." << endl;
753 << "Paragraph " << par->id()
754 << " found in buffer `"
755 << b->fileName() << "'." << endl;
759 setCursor(makeDocIterator(par, 0));
763 // Switch to other buffer view and resend cmd
764 theLyXFunc().dispatch(FuncRequest(
765 LFUN_BUFFER_SWITCH, b->fileName()));
766 theLyXFunc().dispatch(cmd);
775 case LFUN_OUTLINE_UP:
776 toc::outline(toc::Up, cursor_);
777 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
778 updateLabels(*buffer_);
780 case LFUN_OUTLINE_DOWN:
781 toc::outline(toc::Down, cursor_);
782 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
783 updateLabels(*buffer_);
785 case LFUN_OUTLINE_IN:
786 toc::outline(toc::In, cursor_);
787 updateLabels(*buffer_);
789 case LFUN_OUTLINE_OUT:
790 toc::outline(toc::Out, cursor_);
791 updateLabels(*buffer_);
795 bv_funcs::gotoInset(this, InsetBase::NOTE_CODE, false);
798 case LFUN_REFERENCE_NEXT: {
799 vector<InsetBase_code> tmp;
800 tmp.push_back(InsetBase::LABEL_CODE);
801 tmp.push_back(InsetBase::REF_CODE);
802 bv_funcs::gotoInset(this, tmp, true);
806 case LFUN_CHANGES_TRACK:
807 buffer_->params().trackChanges = !buffer_->params().trackChanges;
810 case LFUN_CHANGES_OUTPUT: {
811 buffer_->params().outputChanges = !buffer_->params().outputChanges;
815 case LFUN_CHANGE_NEXT:
816 findNextChange(this);
819 case LFUN_CHANGES_MERGE:
820 if (findNextChange(this))
821 showDialog("changes");
824 case LFUN_ALL_CHANGES_ACCEPT: {
825 cursor_.reset(buffer_->inset());
827 #warning FIXME changes
829 while (findNextChange(this))
830 getLyXText()->acceptChange(cursor_);
835 case LFUN_ALL_CHANGES_REJECT: {
836 cursor_.reset(buffer_->inset());
838 #warning FIXME changes
840 while (findNextChange(this))
841 getLyXText()->rejectChange(cursor_);
849 case LFUN_WORD_REPLACE:
854 cur.clearSelection();
856 cur.message(from_utf8(N_("Mark off")));
860 cur.clearSelection();
863 cur.message(from_utf8(N_("Mark on")));
866 case LFUN_MARK_TOGGLE:
867 cur.clearSelection();
870 cur.message(from_utf8(N_("Mark removed")));
873 cur.message(from_utf8(N_("Mark set")));
878 case LFUN_SCREEN_RECENTER:
882 case LFUN_BIBTEX_DATABASE_ADD: {
883 LCursor tmpcur = cursor_;
884 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
885 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
886 InsetBase::BIBTEX_CODE);
888 if (inset->addDatabase(to_utf8(cmd.argument())))
889 buffer_->updateBibfilesCache();
894 case LFUN_BIBTEX_DATABASE_DEL: {
895 LCursor tmpcur = cursor_;
896 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
897 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
898 InsetBase::BIBTEX_CODE);
900 if (inset->delDatabase(to_utf8(cmd.argument())))
901 buffer_->updateBibfilesCache();
906 case LFUN_WORDS_COUNT: {
907 DocIterator from, to;
908 if (cur.selection()) {
909 from = cur.selectionBegin();
910 to = cur.selectionEnd();
912 from = doc_iterator_begin(buffer_->inset());
913 to = doc_iterator_end(buffer_->inset());
915 int const count = countWords(from, to);
919 message = bformat(_("%1$d words in selection."),
922 message = bformat(_("%1$d words in document."),
927 message = _("One word in selection.");
929 message = _("One word in document.");
932 Alert::information(_("Count words"), message);
936 case LFUN_BUFFER_TOGGLE_COMPRESSION:
937 // turn compression on/off
938 buffer_->params().compressed = !buffer_->params().compressed;
941 case LFUN_NEXT_INSET_TOGGLE: {
942 // this is the real function we want to invoke
943 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
944 // if there is an inset at cursor, see whether it
946 InsetBase * inset = cur.nextInset();
947 if (inset && inset->isActive()) {
948 LCursor tmpcur = cur;
949 tmpcur.pushLeft(*inset);
950 inset->dispatch(tmpcur, tmpcmd);
951 if (tmpcur.result().dispatched()) {
955 // if it did not work, try the underlying inset.
956 if (!cur.result().dispatched())
957 cur.dispatch(tmpcmd);
959 if (cur.result().dispatched())
960 cur.clearSelection();
973 docstring const BufferView::requestSelection()
978 LCursor & cur = cursor_;
980 if (!cur.selection()) {
981 xsel_cache_.set = false;
985 if (!xsel_cache_.set ||
986 cur.top() != xsel_cache_.cursor ||
987 cur.anchor_.top() != xsel_cache_.anchor)
989 xsel_cache_.cursor = cur.top();
990 xsel_cache_.anchor = cur.anchor_.top();
991 xsel_cache_.set = cur.selection();
992 return cur.selectionAsString(false);
998 void BufferView::clearSelection()
1001 cursor_.clearSelection();
1002 xsel_cache_.set = false;
1007 void BufferView::workAreaResize(int width, int height)
1009 bool const widthChange = width != width_;
1010 bool const heightChange = height != height_;
1012 // Update from work area
1023 std::pair<bool, bool> BufferView::workAreaDispatch(FuncRequest const & cmd0)
1025 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1027 // This is only called for mouse related events including
1028 // LFUN_FILE_OPEN generated by drag-and-drop.
1029 FuncRequest cmd = cmd0;
1031 // E.g. Qt mouse press when no buffer
1033 return make_pair(false, false);
1036 cur.push(buffer_->inset());
1037 cur.selection() = cursor_.selection();
1039 // Either the inset under the cursor or the
1040 // surrounding LyXText will handle this event.
1042 // Build temporary cursor.
1043 cmd.y = min(max(cmd.y, -1), height_);
1044 InsetBase * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1046 //lyxerr << BOOST_CURRENT_FUNCTION
1047 // << " * hit inset at tip: " << inset << endl;
1048 //lyxerr << BOOST_CURRENT_FUNCTION
1049 // << " * created temp cursor:" << cur << endl;
1051 // Put anchor at the same position.
1054 // Try to dispatch to an non-editable inset near this position
1055 // via the temp cursor. If the inset wishes to change the real
1056 // cursor it has to do so explicitly by using
1057 // cur.bv().cursor() = cur; (or similar)
1059 inset->dispatch(cur, cmd);
1062 // Now dispatch to the temporary cursor. If the real cursor should
1063 // be modified, the inset's dispatch has to do so explicitly.
1064 if (!cur.result().dispatched())
1067 // Redraw if requested and necessary.
1068 if (cur.result().dispatched() && cur.result().update())
1069 return update(cur.result().update());
1071 // When the above and the inner function are fixed, we can do this:
1072 return make_pair(false, false);
1076 void BufferView::scroll(int /*lines*/)
1081 // LyXText const * t = &buffer_->text();
1082 // int const line_height = defaultRowHeight();
1084 // // The new absolute coordinate
1085 // int new_top_y = top_y() + lines * line_height;
1087 // // Restrict to a valid value
1088 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1089 // new_top_y = std::max(0, new_top_y);
1091 // scrollDocView(new_top_y);
1093 // // Update the scrollbar.
1094 // workArea_->setScrollbarParams(t->height(), top_y(), defaultRowHeight());}
1098 void BufferView::setCursorFromRow(int row)
1103 buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1106 buffer_->text().setCursor(cursor_, 0, 0);
1108 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1112 void BufferView::gotoLabel(docstring const & label)
1114 for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1115 vector<docstring> labels;
1116 it->getLabelList(*buffer_, labels);
1117 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1126 LyXText * BufferView::getLyXText()
1128 LyXText * text = cursor_.innerText();
1134 LyXText const * BufferView::getLyXText() const
1136 LyXText const * text = cursor_.innerText();
1142 int BufferView::workHeight() const
1148 void BufferView::setCursor(DocIterator const & dit)
1150 size_t const n = dit.depth();
1151 for (size_t i = 0; i < n; ++i)
1152 dit[i].inset().edit(cursor_, true);
1154 cursor_.setCursor(dit);
1155 cursor_.selection() = false;
1159 void BufferView::mouseSetCursor(LCursor & cur)
1161 BOOST_ASSERT(&cur.bv() == this);
1163 // Has the cursor just left the inset?
1164 bool badcursor = false;
1165 if (&cursor_.inset() != &cur.inset())
1166 badcursor = cursor_.inset().notifyCursorLeaves(cursor_);
1168 // do the dEPM magic if needed
1169 // FIXME: move this to InsetText::notifyCursorLeaves?
1170 if (!badcursor && cursor_.inTexted())
1171 cursor_.text()->deleteEmptyParagraphMechanism(cur, cursor_);
1174 cursor_.clearSelection();
1175 cursor_.setTargetX();
1181 void BufferView::putSelectionAt(DocIterator const & cur,
1182 int length, bool backwards)
1184 cursor_.clearSelection();
1190 cursor_.pos() += length;
1191 cursor_.setSelection(cursor_, -length);
1193 cursor_.setSelection(cursor_, length);
1198 LCursor & BufferView::cursor()
1204 LCursor const & BufferView::cursor() const
1210 pit_type BufferView::anchor_ref() const
1216 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1218 return metrics_info_;
1222 void BufferView::updateMetrics(bool singlepar)
1224 // Clear out the position cache in case of full screen redraw.
1226 coord_cache_.clear();
1228 LyXText & buftext = buffer_->text();
1229 pit_type size = int(buftext.paragraphs().size());
1231 if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1232 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1236 pit_type const pit = anchor_ref_;
1239 size_t const npit = buftext.paragraphs().size();
1241 // Rebreak anchor paragraph. In Single Paragraph mode, rebreak only
1242 // the (main text, not inset!) paragraph containing the cursor.
1243 // (if this paragraph contains insets etc., rebreaking will
1244 // recursively descend)
1245 if (!singlepar || pit == cursor_.bottom().pit())
1246 buftext.redoParagraph(*this, pit);
1247 int y0 = buftext.getPar(pit).ascent() - offset_ref_;
1249 // Redo paragraphs above anchor if necessary; again, in Single Par
1250 // mode, only if we encounter the (main text) one having the cursor.
1252 while (y1 > 0 && pit1 > 0) {
1253 y1 -= buftext.getPar(pit1).ascent();
1255 if (!singlepar || pit1 == cursor_.bottom().pit())
1256 buftext.redoParagraph(*this, pit1);
1257 y1 -= buftext.getPar(pit1).descent();
1261 // Take care of ascent of first line
1262 y1 -= buftext.getPar(pit1).ascent();
1264 // Normalize anchor for next time
1268 // Grey at the beginning is ugly
1269 if (pit1 == 0 && y1 > 0) {
1275 // Redo paragraphs below the anchor if necessary. Single par mode:
1276 // only the one containing the cursor if encountered.
1278 while (y2 < height_ && pit2 < int(npit) - 1) {
1279 y2 += buftext.getPar(pit2).descent();
1281 if (!singlepar || pit2 == cursor_.bottom().pit())
1282 buftext.redoParagraph(*this, pit2);
1283 y2 += buftext.getPar(pit2).ascent();
1286 // Take care of descent of last line
1287 y2 += buftext.getPar(pit2).descent();
1289 // The coordinates of all these paragraphs are correct, cache them
1291 CoordCache::InnerParPosCache & parPos = coord_cache_.parPos()[&buftext];
1292 for (pit_type pit = pit1; pit <= pit2; ++pit) {
1293 Paragraph const & par = buftext.getPar(pit);
1295 parPos[pit] = Point(0, y);
1296 if (singlepar && pit == cursor_.bottom().pit()) {
1297 // In Single Paragraph mode, collect here the
1298 // y1 and y2 of the (one) paragraph the cursor is in
1299 y1 = y - par.ascent();
1300 y2 = y + par.descent();
1306 // collect cursor paragraph iter bounds
1307 pit1 = cursor_.bottom().pit();
1308 pit2 = cursor_.bottom().pit();
1311 lyxerr[Debug::DEBUG]
1312 << BOOST_CURRENT_FUNCTION
1315 << " pit1: " << pit1
1316 << " pit2: " << pit2
1317 << " npit: " << npit
1318 << " singlepar: " << singlepar
1322 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2, singlepar, size);
1324 if (lyxerr.debugging(Debug::WORKAREA)) {
1325 lyxerr[Debug::WORKAREA] << "BufferView::updateMetrics" << endl;
1326 coord_cache_.dump();
1331 void BufferView::menuInsertLyXFile(string const & filenm)
1333 BOOST_ASSERT(cursor_.inTexted());
1334 string filename = filenm;
1336 if (filename.empty()) {
1337 // Launch a file browser
1339 string initpath = lyxrc.document_path;
1342 string const trypath = buffer_->filePath();
1343 // If directory is writeable, use this as default.
1344 if (isDirWriteable(trypath))
1349 FileDialog fileDlg(_("Select LyX document to insert"),
1351 make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1352 make_pair(_("Examples|#E#e"), from_utf8(addPath(package().system_support(), "examples"))));
1354 FileDialog::Result result =
1355 fileDlg.open(from_utf8(initpath),
1356 FileFilterList(_("LyX Documents (*.lyx)")),
1359 if (result.first == FileDialog::Later)
1363 filename = to_utf8(result.second);
1365 // check selected filename
1366 if (filename.empty()) {
1367 // emit message signal.
1368 message(_("Canceled."));
1373 // Get absolute path of file and add ".lyx"
1374 // to the filename if necessary
1375 filename = fileSearch(string(), filename, "lyx");
1377 docstring const disp_fn = makeDisplayPath(filename);
1378 // emit message signal.
1379 message(bformat(_("Inserting document %1$s..."), disp_fn));
1382 Buffer buf("", false);
1383 if (lyx::loadLyXFile(&buf, makeAbsPath(filename))) {
1384 ErrorList & el = buffer_->errorList("Parse");
1385 // Copy the inserted document error list into the current buffer one.
1386 el = buf.errorList("Parse");
1387 recordUndo(cursor_);
1388 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1389 buf.params().textclass, el);
1390 res = _("Document %1$s inserted.");
1392 res = _("Could not insert document %1$s");
1394 // emit message signal.
1395 message(bformat(res, disp_fn));
1396 buffer_->errors("Parse");