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 unsigned int const saved_positions_num = 20;
109 /// Return an inset of this class if it exists at the current cursor position
111 T * getInsetByCode(LCursor & cur, InsetBase::Code code)
114 DocIterator it = cur;
115 if (it.nextInset() &&
116 it.nextInset()->lyxCode() == code) {
117 inset = static_cast<T*>(it.nextInset());
125 BufferView::BufferView()
126 : buffer_(0), wh_(0), width_(0), height_(0),
128 multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
131 xsel_cache_.set = false;
133 saved_positions.resize(saved_positions_num);
134 // load saved bookmarks
135 Session::BookmarkList & bmList = LyX::ref().session().loadBookmarks();
136 for (Session::BookmarkList::iterator bm = bmList.begin();
137 bm != bmList.end(); ++bm)
138 if (bm->get<0>() < saved_positions_num)
139 saved_positions[bm->get<0>()] = Position( bm->get<1>(), bm->get<2>(), bm->get<3>() );
140 // and then clear them
143 intl_->initKeyMapper(lyxrc.use_kbmap);
147 BufferView::~BufferView()
152 Buffer * BufferView::buffer() const
158 void BufferView::setBuffer(Buffer * b)
160 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
161 << "[ b = " << b << "]" << endl;
164 // Save the actual cursor position and anchor inside the
165 // buffer so that it can be restored in case we rechange
166 // to this buffer later on.
167 buffer_->saveCursor(cursor_.selectionBegin(),
168 cursor_.selectionEnd());
169 // current buffer is going to be switched-off, save cursor pos
170 LyX::ref().session().saveFilePosition(buffer_->fileName(),
171 boost::tie(cursor_.pit(), cursor_.pos()) );
174 // If we're quitting lyx, don't bother updating stuff
180 // If we are closing current buffer, switch to the first in
183 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
184 << " No Buffer!" << endl;
185 // We are closing the buffer, use the first buffer as current
186 buffer_ = theBufferList().first();
188 // Set current buffer
193 cursor_ = LCursor(*this);
198 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
199 << "Buffer addr: " << buffer_ << endl;
200 cursor_.push(buffer_->inset());
201 cursor_.resetAnchor();
202 buffer_->text().init(this);
203 buffer_->text().setCurrentFont(cursor_);
204 if (buffer_->getCursor().size() > 0 &&
205 buffer_->getAnchor().size() > 0)
207 cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
208 cursor_.resetAnchor();
209 cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
210 cursor_.setSelection();
216 if (buffer_ && graphics::Previews::status() != LyXRC::PREVIEW_OFF)
217 graphics::Previews::get().generateBufferPreviews(*buffer_);
221 bool BufferView::loadLyXFile(string const & filename, bool tolastfiles)
223 // Get absolute path of file and add ".lyx"
224 // to the filename if necessary
225 string s = fileSearch(string(), filename, "lyx");
227 bool const found = !s.empty();
232 // File already open?
233 if (theBufferList().exists(s)) {
234 docstring const file = makeDisplayPath(s, 20);
235 docstring text = bformat(_("The document %1$s is already "
236 "loaded.\n\nDo you want to revert "
237 "to the saved version?"), file);
238 int const ret = Alert::prompt(_("Revert to saved document?"),
239 text, 0, 1, _("&Revert"), _("&Switch to document"));
242 setBuffer(theBufferList().getBuffer(s));
245 // FIXME: should be LFUN_REVERT
246 if (!theBufferList().close(theBufferList().getBuffer(s), false))
248 // Fall through to new load. (Asger)
254 b = theBufferList().newBuffer(s);
255 if (!lyx::loadLyXFile(b, s)) {
256 theBufferList().release(b);
260 docstring text = bformat(_("The document %1$s does not yet "
261 "exist.\n\nDo you want to create "
262 "a new document?"), from_utf8(s));
263 int const ret = Alert::prompt(_("Create new document?"),
264 text, 0, 1, _("&Create"), _("Cancel"));
267 b = newFile(s, string(), true);
275 // Send the "errors" signal in case of parsing errors
278 // scroll to the position when the file was last closed
279 if (lyxrc.use_lastfilepos) {
282 boost::tie(pit, pos) = LyX::ref().session().loadFilePosition(s);
283 // I am not sure how to separate the following part to a function
284 // so I will leave this to Lars.
286 // check pit since the document may be externally changed.
287 if ( static_cast<size_t>(pit) < b->paragraphs().size() ) {
288 ParIterator it = b->par_iterator_begin();
289 ParIterator const end = b->par_iterator_end();
290 for (; it != end; ++it)
291 if (it.pit() == pit) {
292 // restored pos may be bigger than it->size
293 setCursor(makeDocIterator(it, min(pos, it->size())));
294 update(Update::FitCursor);
301 LyX::ref().session().addLastFile(b->fileName());
307 void BufferView::reload()
309 string const fn = buffer_->fileName();
310 if (theBufferList().close(buffer_, false))
315 void BufferView::resize()
320 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
322 buffer_->text().init(this);
328 bool BufferView::fitCursor()
330 if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
331 frontend::FontMetrics const & fm =
332 theFontMetrics(cursor_.getFont());
333 int const asc = fm.maxAscent();
334 int const des = fm.maxDescent();
335 Point const p = bv_funcs::getPos(*this, cursor_, cursor_.boundary());
336 if (p.y_ - asc >= 0 && p.y_ + des < height_)
344 bool BufferView::multiParSel()
346 if (!cursor_.selection())
348 bool ret = multiparsel_cache_;
349 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
350 // Either this, or previous selection spans paragraphs
351 return ret || multiparsel_cache_;
355 bool BufferView::update(Update::flags flags)
357 // This is close to a hot-path.
358 if (lyxerr.debugging(Debug::DEBUG)) {
360 << BOOST_CURRENT_FUNCTION
361 << "[fitcursor = " << (flags & Update::FitCursor)
362 << ", forceupdate = " << (flags & Update::Force)
363 << ", singlepar = " << (flags & Update::SinglePar)
364 << "] buffer: " << buffer_ << endl;
367 // Check needed to survive LyX startup
371 lyxerr[Debug::WORKAREA] << "BufferView::update" << std::endl;
373 // Update macro store
374 buffer_->buildMacros();
376 // First drawing step
377 updateMetrics(flags & Update::SinglePar);
379 // The second drawing step is done in WorkArea::redraw() if needed.
380 bool const need_second_step =
381 (flags & (Update::Force | Update::FitCursor | Update::MultiParSel))
382 && (fitCursor() || multiParSel());
384 return need_second_step;
388 void BufferView::updateScrollbar()
391 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
392 << " no text in updateScrollbar" << endl;
393 scrollbarParameters_.reset();
397 LyXText & t = buffer_->text();
398 int const parsize = int(t.paragraphs().size() - 1);
399 if (anchor_ref_ > parsize) {
400 anchor_ref_ = parsize;
405 << BOOST_CURRENT_FUNCTION
406 << " Updating scrollbar: height: " << t.paragraphs().size()
407 << " curr par: " << cursor_.bottom().pit()
408 << " default height " << defaultRowHeight() << endl;
410 // It would be better to fix the scrollbar to understand
411 // values in [0..1] and divide everything by wh
413 // estimated average paragraph height:
416 int h = t.getPar(anchor_ref_).height();
418 // Normalize anchor/offset (MV):
419 while (offset_ref_ > h && anchor_ref_ < parsize) {
422 h = t.getPar(anchor_ref_).height();
424 // Look at paragraph heights on-screen
427 for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
430 int const h2 = t.getPar(pit).height();
436 int const hav = sumh / nh;
437 // More realistic average paragraph height
442 scrollbarParameters_.height = (parsize + 1) * wh_;
443 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
444 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
448 ScrollbarParameters const & BufferView::scrollbarParameters() const
450 return scrollbarParameters_;
454 void BufferView::scrollDocView(int value)
456 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
457 << "[ value = " << value << "]" << endl;
462 LyXText & t = buffer_->text();
464 float const bar = value / float(wh_ * t.paragraphs().size());
466 anchor_ref_ = int(bar * t.paragraphs().size());
467 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
468 anchor_ref_ = int(t.paragraphs().size()) - 1;
469 t.redoParagraph(anchor_ref_);
470 int const h = t.getPar(anchor_ref_).height();
471 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
475 void BufferView::setCursorFromScrollbar()
477 LyXText & t = buffer_->text();
479 int const height = 2 * defaultRowHeight();
480 int const first = height;
481 int const last = height_ - height;
482 LCursor & cur = cursor_;
484 bv_funcs::CurStatus st = bv_funcs::status(this, cur);
487 case bv_funcs::CUR_ABOVE:
488 t.setCursorFromCoordinates(cur, 0, first);
489 cur.clearSelection();
491 case bv_funcs::CUR_BELOW:
492 t.setCursorFromCoordinates(cur, 0, last);
493 cur.clearSelection();
495 case bv_funcs::CUR_INSIDE:
496 int const y = bv_funcs::getPos(*this, cur, cur.boundary()).y_;
497 int const newy = min(last, max(y, first));
499 cur.reset(buffer_->inset());
500 t.setCursorFromCoordinates(cur, 0, newy);
506 Change const BufferView::getCurrentChange() const
508 if (!cursor_.selection())
509 return Change(Change::UNCHANGED);
511 DocIterator dit = cursor_.selectionBegin();
512 return dit.paragraph().lookupChange(dit.pos());
516 void BufferView::savePosition(unsigned int i)
518 if (i >= saved_positions_num)
520 BOOST_ASSERT(cursor_.inTexted());
521 saved_positions[i] = Position(buffer_->fileName(),
522 cursor_.paragraph().id(),
525 // emit message signal.
526 message(bformat(_("Saved bookmark %1$d"), i));
530 void BufferView::restorePosition(unsigned int i)
532 if (i >= saved_positions_num)
535 string const fname = saved_positions[i].filename;
537 cursor_.clearSelection();
539 if (fname != buffer_->fileName()) {
541 if (theBufferList().exists(fname))
542 b = theBufferList().getBuffer(fname);
544 b = theBufferList().newBuffer(fname);
545 // Don't ask, just load it
546 lyx::loadLyXFile(b, fname);
552 ParIterator par = buffer_->getParFromID(saved_positions[i].par_id);
553 if (par == buffer_->par_iterator_end())
556 setCursor(makeDocIterator(par, min(par->size(), saved_positions[i].par_pos)));
559 // emit message signal.
560 message(bformat(_("Moved to bookmark %1$d"), i));
564 bool BufferView::isSavedPosition(unsigned int i)
566 return i < saved_positions_num && !saved_positions[i].filename.empty();
569 void BufferView::saveSavedPositions()
571 // save bookmarks. It is better to use the pit interface
572 // but I do not know how to effectively convert between
574 for (unsigned int i=1; i < saved_positions_num; ++i) {
575 if ( isSavedPosition(i) )
576 LyX::ref().session().saveBookmark( boost::tie(
578 saved_positions[i].filename,
579 saved_positions[i].par_id,
580 saved_positions[i].par_pos) );
584 void BufferView::switchKeyMap()
586 if (!lyxrc.rtl_support)
589 if (getLyXText()->real_current_font.isRightToLeft()) {
590 if (intl_->keymap == Intl::PRIMARY)
593 if (intl_->keymap == Intl::SECONDARY)
599 int BufferView::workWidth() const
605 void BufferView::center()
607 CursorSlice & bot = cursor_.bottom();
608 pit_type const pit = bot.pit();
609 bot.text()->redoParagraph(pit);
610 Paragraph const & par = bot.text()->paragraphs()[pit];
612 offset_ref_ = bv_funcs::coordOffset(*this, cursor_, cursor_.boundary()).y_
613 + par.ascent() - height_ / 2;
617 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
621 switch (cmd.action) {
624 flag.enabled(!buffer_->undostack().empty());
627 flag.enabled(!buffer_->redostack().empty());
629 case LFUN_FILE_INSERT:
630 case LFUN_FILE_INSERT_ASCII_PARA:
631 case LFUN_FILE_INSERT_ASCII:
632 case LFUN_BOOKMARK_SAVE:
633 // FIXME: Actually, these LFUNS should be moved to LyXText
634 flag.enabled(cursor_.inTexted());
636 case LFUN_FONT_STATE:
637 case LFUN_LABEL_INSERT:
638 case LFUN_PARAGRAPH_GOTO:
639 // FIXME handle non-trivially
640 case LFUN_OUTLINE_UP:
641 case LFUN_OUTLINE_DOWN:
642 case LFUN_OUTLINE_IN:
643 case LFUN_OUTLINE_OUT:
645 case LFUN_REFERENCE_NEXT:
647 case LFUN_WORD_REPLACE:
650 case LFUN_MARK_TOGGLE:
651 case LFUN_SCREEN_RECENTER:
652 case LFUN_BIBTEX_DATABASE_ADD:
653 case LFUN_BIBTEX_DATABASE_DEL:
654 case LFUN_WORDS_COUNT:
655 case LFUN_NEXT_INSET_TOGGLE:
659 case LFUN_LABEL_GOTO: {
660 flag.enabled(!cmd.argument().empty()
661 || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
665 case LFUN_BOOKMARK_GOTO:
666 flag.enabled(isSavedPosition(convert<unsigned int>(to_utf8(cmd.argument()))));
669 case LFUN_CHANGES_TRACK:
671 flag.setOnOff(buffer_->params().trackChanges);
674 case LFUN_CHANGES_OUTPUT: {
675 OutputParams runparams;
676 LaTeXFeatures features(*buffer_, buffer_->params(), runparams);
677 flag.enabled(buffer_ && features.isAvailable("dvipost"));
678 flag.setOnOff(buffer_->params().outputChanges);
682 case LFUN_CHANGES_MERGE:
683 case LFUN_CHANGE_NEXT:
684 case LFUN_ALL_CHANGES_ACCEPT:
685 case LFUN_ALL_CHANGES_REJECT:
686 flag.enabled(buffer_); // FIXME: Change tracking (MG)
689 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
690 flag.setOnOff(buffer_->params().compressed);
702 bool BufferView::dispatch(FuncRequest const & cmd)
704 //lyxerr << BOOST_CURRENT_FUNCTION
705 // << [ cmd = " << cmd << "]" << endl;
707 // Make sure that the cached BufferView is correct.
708 lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
709 << " action[" << cmd.action << ']'
710 << " arg[" << to_utf8(cmd.argument()) << ']'
711 << " x[" << cmd.x << ']'
712 << " y[" << cmd.y << ']'
713 << " button[" << cmd.button() << ']'
716 LCursor & cur = cursor_;
718 switch (cmd.action) {
722 cur.message(_("Undo"));
723 cur.clearSelection();
724 if (!textUndo(*this))
725 cur.message(_("No further undo information"));
733 cur.message(_("Redo"));
734 cur.clearSelection();
735 if (!textRedo(*this))
736 cur.message(_("No further redo information"));
742 case LFUN_FILE_INSERT:
743 // FIXME: We don't know the encoding of filenames
744 menuInsertLyXFile(to_utf8(cmd.argument()));
747 case LFUN_FILE_INSERT_ASCII_PARA:
748 // FIXME: We don't know the encoding of filenames
749 insertAsciiFile(this, to_utf8(cmd.argument()), true);
752 case LFUN_FILE_INSERT_ASCII:
753 // FIXME: We don't know the encoding of filenames
754 insertAsciiFile(this, to_utf8(cmd.argument()), false);
757 case LFUN_FONT_STATE:
758 cur.message(from_utf8(cur.currentState()));
761 case LFUN_BOOKMARK_SAVE:
762 savePosition(convert<unsigned int>(to_utf8(cmd.argument())));
765 case LFUN_BOOKMARK_GOTO:
766 restorePosition(convert<unsigned int>(to_utf8(cmd.argument())));
769 case LFUN_LABEL_GOTO: {
770 docstring label = cmd.argument();
773 getInsetByCode<InsetRef>(cursor_,
774 InsetBase::REF_CODE);
776 label = inset->getParam("reference");
786 case LFUN_PARAGRAPH_GOTO: {
787 int const id = convert<int>(to_utf8(cmd.argument()));
788 ParIterator par = buffer_->getParFromID(id);
789 if (par == buffer_->par_iterator_end()) {
790 lyxerr[Debug::INFO] << "No matching paragraph found! ["
791 << id << ']' << endl;
794 lyxerr[Debug::INFO] << "Paragraph " << par->id()
795 << " found." << endl;
799 setCursor(makeDocIterator(par, 0));
806 case LFUN_OUTLINE_UP:
807 toc::outline(toc::Up, cursor_);
808 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
809 updateLabels(*buffer_);
811 case LFUN_OUTLINE_DOWN:
812 toc::outline(toc::Down, cursor_);
813 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
814 updateLabels(*buffer_);
816 case LFUN_OUTLINE_IN:
817 toc::outline(toc::In, cursor_);
818 updateLabels(*buffer_);
820 case LFUN_OUTLINE_OUT:
821 toc::outline(toc::Out, cursor_);
822 updateLabels(*buffer_);
826 bv_funcs::gotoInset(this, InsetBase::NOTE_CODE, false);
829 case LFUN_REFERENCE_NEXT: {
830 vector<InsetBase_code> tmp;
831 tmp.push_back(InsetBase::LABEL_CODE);
832 tmp.push_back(InsetBase::REF_CODE);
833 bv_funcs::gotoInset(this, tmp, true);
837 case LFUN_CHANGES_TRACK:
838 buffer_->params().trackChanges = !buffer_->params().trackChanges;
841 case LFUN_CHANGES_OUTPUT: {
842 buffer_->params().outputChanges = !buffer_->params().outputChanges;
846 case LFUN_CHANGE_NEXT:
847 findNextChange(this);
850 case LFUN_CHANGES_MERGE:
851 if (findNextChange(this))
852 showDialog("changes");
855 case LFUN_ALL_CHANGES_ACCEPT: {
856 cursor_.reset(buffer_->inset());
858 #warning FIXME changes
860 while (findNextChange(this))
861 getLyXText()->acceptChange(cursor_);
866 case LFUN_ALL_CHANGES_REJECT: {
867 cursor_.reset(buffer_->inset());
869 #warning FIXME changes
871 while (findNextChange(this))
872 getLyXText()->rejectChange(cursor_);
880 case LFUN_WORD_REPLACE:
885 cur.clearSelection();
887 cur.message(from_utf8(N_("Mark off")));
891 cur.clearSelection();
894 cur.message(from_utf8(N_("Mark on")));
897 case LFUN_MARK_TOGGLE:
898 cur.clearSelection();
901 cur.message(from_utf8(N_("Mark removed")));
904 cur.message(from_utf8(N_("Mark set")));
909 case LFUN_SCREEN_RECENTER:
913 case LFUN_BIBTEX_DATABASE_ADD: {
914 LCursor tmpcur = cursor_;
915 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
916 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
917 InsetBase::BIBTEX_CODE);
919 if (inset->addDatabase(to_utf8(cmd.argument())))
920 buffer_->updateBibfilesCache();
925 case LFUN_BIBTEX_DATABASE_DEL: {
926 LCursor tmpcur = cursor_;
927 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
928 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
929 InsetBase::BIBTEX_CODE);
931 if (inset->delDatabase(to_utf8(cmd.argument())))
932 buffer_->updateBibfilesCache();
937 case LFUN_WORDS_COUNT: {
938 DocIterator from, to;
939 if (cur.selection()) {
940 from = cur.selectionBegin();
941 to = cur.selectionEnd();
943 from = doc_iterator_begin(buffer_->inset());
944 to = doc_iterator_end(buffer_->inset());
946 int const count = countWords(from, to);
950 message = bformat(_("%1$d words in selection."),
953 message = bformat(_("%1$d words in document."),
958 message = _("One word in selection.");
960 message = _("One word in document.");
963 Alert::information(_("Count words"), message);
967 case LFUN_BUFFER_TOGGLE_COMPRESSION:
968 // turn compression on/off
969 buffer_->params().compressed = !buffer_->params().compressed;
972 case LFUN_NEXT_INSET_TOGGLE: {
973 // this is the real function we want to invoke
974 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
975 // if there is an inset at cursor, see whether it
977 InsetBase * inset = cur.nextInset();
978 if (inset && inset->isActive()) {
979 LCursor tmpcur = cur;
980 tmpcur.pushLeft(*inset);
981 inset->dispatch(tmpcur, tmpcmd);
982 if (tmpcur.result().dispatched()) {
986 // if it did not work, try the underlying inset.
987 if (!cur.result().dispatched())
988 cur.dispatch(tmpcmd);
990 if (cur.result().dispatched())
991 cur.clearSelection();
1004 docstring const BufferView::requestSelection()
1009 LCursor & cur = cursor_;
1011 if (!cur.selection()) {
1012 xsel_cache_.set = false;
1016 if (!xsel_cache_.set ||
1017 cur.top() != xsel_cache_.cursor ||
1018 cur.anchor_.top() != xsel_cache_.anchor)
1020 xsel_cache_.cursor = cur.top();
1021 xsel_cache_.anchor = cur.anchor_.top();
1022 xsel_cache_.set = cur.selection();
1023 return cur.selectionAsString(false);
1029 void BufferView::clearSelection()
1032 cursor_.clearSelection();
1033 xsel_cache_.set = false;
1038 void BufferView::workAreaResize(int width, int height)
1040 bool const widthChange = width != width_;
1041 bool const heightChange = height != height_;
1043 // Update from work area
1047 if (buffer_ && widthChange) {
1048 // The WorkArea content needs a resize
1052 if (widthChange || heightChange)
1057 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1059 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1061 // This is only called for mouse related events including
1062 // LFUN_FILE_OPEN generated by drag-and-drop.
1063 FuncRequest cmd = cmd0;
1069 cur.push(buffer_->inset());
1070 cur.selection() = cursor_.selection();
1072 // Doesn't go through lyxfunc, so we need to update
1073 // the layout choice etc. ourselves
1075 // E.g. Qt mouse press when no buffer
1079 // Either the inset under the cursor or the
1080 // surrounding LyXText will handle this event.
1082 // Build temporary cursor.
1083 cmd.y = min(max(cmd.y, -1), height_);
1084 InsetBase * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1085 //lyxerr << BOOST_CURRENT_FUNCTION
1086 // << " * hit inset at tip: " << inset << endl;
1087 //lyxerr << BOOST_CURRENT_FUNCTION
1088 // << " * created temp cursor:" << cur << endl;
1090 // Put anchor at the same position.
1093 // Try to dispatch to an non-editable inset near this position
1094 // via the temp cursor. If the inset wishes to change the real
1095 // cursor it has to do so explicitly by using
1096 // cur.bv().cursor() = cur; (or similar)
1098 inset->dispatch(cur, cmd);
1100 // Now dispatch to the temporary cursor. If the real cursor should
1101 // be modified, the inset's dispatch has to do so explicitly.
1102 if (!cur.result().dispatched())
1105 if (cur.result().dispatched()) {
1106 // Redraw if requested or necessary.
1107 if (cur.result().update())
1108 update(Update::FitCursor | Update::Force);
1110 update(Update::FitCursor | Update::MultiParSel);
1117 void BufferView::scroll(int /*lines*/)
1122 // LyXText const * t = &buffer_->text();
1123 // int const line_height = defaultRowHeight();
1125 // // The new absolute coordinate
1126 // int new_top_y = top_y() + lines * line_height;
1128 // // Restrict to a valid value
1129 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1130 // new_top_y = std::max(0, new_top_y);
1132 // scrollDocView(new_top_y);
1134 // // Update the scrollbar.
1135 // workArea_->setScrollbarParams(t->height(), top_y(), defaultRowHeight());}
1139 void BufferView::setCursorFromRow(int row)
1144 buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1147 buffer_->text().setCursor(cursor_, 0, 0);
1149 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1153 void BufferView::gotoLabel(docstring const & label)
1155 for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1156 vector<docstring> labels;
1157 it->getLabelList(*buffer_, labels);
1158 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1167 LyXText * BufferView::getLyXText()
1169 LyXText * text = cursor_.innerText();
1175 LyXText const * BufferView::getLyXText() const
1177 LyXText const * text = cursor_.innerText();
1183 int BufferView::workHeight() const
1189 void BufferView::setCursor(DocIterator const & dit)
1191 size_t const n = dit.depth();
1192 for (size_t i = 0; i < n; ++i)
1193 dit[i].inset().edit(cursor_, true);
1195 cursor_.setCursor(dit);
1196 cursor_.selection() = false;
1200 void BufferView::mouseSetCursor(LCursor & cur)
1202 BOOST_ASSERT(&cur.bv() == this);
1204 // Has the cursor just left the inset?
1205 bool badcursor = false;
1206 if (&cursor_.inset() != &cur.inset())
1207 badcursor = cursor_.inset().notifyCursorLeaves(cursor_);
1209 // do the dEPM magic if needed
1210 // FIXME: move this to InsetText::notifyCursorLeaves?
1211 if (!badcursor && cursor_.inTexted())
1212 cursor_.text()->deleteEmptyParagraphMechanism(cur, cursor_);
1215 cursor_.clearSelection();
1216 cursor_.setTargetX();
1222 void BufferView::putSelectionAt(DocIterator const & cur,
1223 int length, bool backwards)
1225 cursor_.clearSelection();
1231 cursor_.pos() += length;
1232 cursor_.setSelection(cursor_, -length);
1234 cursor_.setSelection(cursor_, length);
1239 LCursor & BufferView::cursor()
1245 LCursor const & BufferView::cursor() const
1251 pit_type BufferView::anchor_ref() const
1257 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1259 return metrics_info_;
1263 void BufferView::updateMetrics(bool singlepar)
1265 // FIXME (Abdel 19/10/2006):
1266 // There's something fishy in tabular. The coord_cache_ is not
1267 // correctly reconstructed when a character is trying to be inserted.
1268 // Not clearing out the coord_cache_ fixes the crash but there is a
1269 // bad side effect: buffer-begin and buffer-end do not update the screen.
1271 // Remove old position cache
1272 coord_cache_.clear();
1274 LyXText & buftext = buffer_->text();
1275 pit_type size = int(buftext.paragraphs().size());
1277 if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1278 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1282 pit_type const pit = anchor_ref_;
1285 size_t const npit = buftext.paragraphs().size();
1287 // Rebreak anchor paragraph. In Single Paragraph mode, rebreak only
1288 // the (main text, not inset!) paragraph containing the cursor.
1289 // (if this paragraph contains insets etc., rebreaking will
1290 // recursively descend)
1291 if (!singlepar || pit == cursor_.bottom().pit())
1292 buftext.redoParagraph(pit);
1293 int y0 = buftext.getPar(pit).ascent() - offset_ref_;
1295 // Redo paragraphs above anchor if necessary; again, in Single Par
1296 // mode, only if we encounter the (main text) one having the cursor.
1298 while (y1 > 0 && pit1 > 0) {
1299 y1 -= buftext.getPar(pit1).ascent();
1301 if (!singlepar || pit1 == cursor_.bottom().pit())
1302 buftext.redoParagraph(pit1);
1303 y1 -= buftext.getPar(pit1).descent();
1307 // Take care of ascent of first line
1308 y1 -= buftext.getPar(pit1).ascent();
1310 // Normalize anchor for next time
1314 // Grey at the beginning is ugly
1315 if (pit1 == 0 && y1 > 0) {
1321 // Redo paragraphs below the anchor if necessary. Single par mode:
1322 // only the one containing the cursor if encountered.
1324 while (y2 < height_ && pit2 < int(npit) - 1) {
1325 y2 += buftext.getPar(pit2).descent();
1327 if (!singlepar || pit2 == cursor_.bottom().pit())
1328 buftext.redoParagraph(pit2);
1329 y2 += buftext.getPar(pit2).ascent();
1332 // Take care of descent of last line
1333 y2 += buftext.getPar(pit2).descent();
1335 // The coordinates of all these paragraphs are correct, cache them
1337 CoordCache::InnerParPosCache & parPos = coord_cache_.parPos()[&buftext];
1338 for (pit_type pit = pit1; pit <= pit2; ++pit) {
1339 Paragraph const & par = buftext.getPar(pit);
1341 parPos[pit] = Point(0, y);
1342 if (singlepar && pit == cursor_.bottom().pit()) {
1343 // In Single Paragraph mode, collect here the
1344 // y1 and y2 of the (one) paragraph the cursor is in
1345 y1 = y - par.ascent();
1346 y2 = y + par.descent();
1352 // collect cursor paragraph iter bounds
1353 pit1 = cursor_.bottom().pit();
1354 pit2 = cursor_.bottom().pit();
1357 lyxerr[Debug::DEBUG]
1358 << BOOST_CURRENT_FUNCTION
1361 << " pit1: " << pit1
1362 << " pit2: " << pit2
1363 << " npit: " << npit
1364 << " singlepar: " << singlepar
1368 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2, singlepar, size);
1370 if (lyxerr.debugging(Debug::WORKAREA)) {
1371 lyxerr[Debug::WORKAREA] << "BufferView::updateMetrics" << endl;
1372 coord_cache_.dump();
1377 void BufferView::menuInsertLyXFile(string const & filenm)
1379 BOOST_ASSERT(cursor_.inTexted());
1380 string filename = filenm;
1382 if (filename.empty()) {
1383 // Launch a file browser
1385 string initpath = lyxrc.document_path;
1388 string const trypath = buffer_->filePath();
1389 // If directory is writeable, use this as default.
1390 if (isDirWriteable(trypath))
1395 FileDialog fileDlg(_("Select LyX document to insert"),
1397 make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1398 make_pair(_("Examples|#E#e"), from_utf8(addPath(package().system_support(), "examples"))));
1400 FileDialog::Result result =
1401 fileDlg.open(from_utf8(initpath),
1402 FileFilterList(_("LyX Documents (*.lyx)")),
1405 if (result.first == FileDialog::Later)
1409 filename = to_utf8(result.second);
1411 // check selected filename
1412 if (filename.empty()) {
1413 // emit message signal.
1414 message(_("Canceled."));
1419 // Get absolute path of file and add ".lyx"
1420 // to the filename if necessary
1421 filename = fileSearch(string(), filename, "lyx");
1423 docstring const disp_fn = makeDisplayPath(filename);
1424 // emit message signal.
1425 message(bformat(_("Inserting document %1$s..."), disp_fn));
1428 Buffer buf("", false);
1429 if (lyx::loadLyXFile(&buf, makeAbsPath(filename))) {
1430 ErrorList & el = buffer_->errorList("Parse");
1431 // Copy the inserted document error list into the current buffer one.
1432 el = buf.errorList("Parse");
1433 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1434 buf.params().textclass, el);
1435 res = _("Document %1$s inserted.");
1437 res = _("Could not insert document %1$s");
1439 // emit message signal.
1440 message(bformat(res, disp_fn));
1441 buffer_->errors("Parse");