3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
7 * \author Stefan Schimanski
9 * Full author contact details are available in file CREDITS.
17 #include "LayoutFile.h"
18 #include "BiblioInfo.h"
19 #include "BranchList.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
25 #include "Converter.h"
27 #include "DocIterator.h"
29 #include "ErrorList.h"
32 #include "FuncRequest.h"
33 #include "InsetIterator.h"
34 #include "InsetList.h"
36 #include "LaTeXFeatures.h"
40 #include "LyXAction.h"
44 #include "output_docbook.h"
46 #include "output_latex.h"
47 #include "output_plaintext.h"
48 #include "paragraph_funcs.h"
49 #include "Paragraph.h"
50 #include "ParagraphParameters.h"
51 #include "ParIterator.h"
52 #include "PDFOptions.h"
55 #include "TexStream.h"
57 #include "TextClass.h"
58 #include "TocBackend.h"
60 #include "VCBackend.h"
64 #include "insets/InsetBibitem.h"
65 #include "insets/InsetBibtex.h"
66 #include "insets/InsetInclude.h"
67 #include "insets/InsetText.h"
69 #include "mathed/MacroTable.h"
70 #include "mathed/MathMacroTemplate.h"
71 #include "mathed/MathSupport.h"
73 #include "frontends/alert.h"
74 #include "frontends/Delegates.h"
75 #include "frontends/WorkAreaManager.h"
77 #include "graphics/Previews.h"
79 #include "support/lassert.h"
80 #include "support/convert.h"
81 #include "support/debug.h"
82 #include "support/ExceptionMessage.h"
83 #include "support/FileName.h"
84 #include "support/FileNameList.h"
85 #include "support/filetools.h"
86 #include "support/ForkedCalls.h"
87 #include "support/gettext.h"
88 #include "support/gzstream.h"
89 #include "support/lstrings.h"
90 #include "support/lyxalgo.h"
91 #include "support/os.h"
92 #include "support/Package.h"
93 #include "support/Path.h"
94 #include "support/textutils.h"
95 #include "support/types.h"
97 #include <boost/bind.hpp>
98 #include <boost/shared_ptr.hpp>
110 using namespace lyx::support;
114 namespace Alert = frontend::Alert;
115 namespace os = support::os;
119 // Do not remove the comment below, so we get merge conflict in
120 // independent branches. Instead add your own.
121 int const LYX_FORMAT = 348; // uwestoehr: add support for \*phantom
123 typedef map<string, bool> DepClean;
124 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
128 class BufferSet : public std::set<Buffer const *> {};
133 Impl(Buffer & parent, FileName const & file, bool readonly);
147 mutable TexRow texrow;
148 Buffer const * parent_buffer;
150 /// need to regenerate .tex?
154 mutable bool lyx_clean;
156 /// is autosave needed?
157 mutable bool bak_clean;
159 /// is this a unnamed file (New...)?
165 /// name of the file the buffer is associated with.
168 /** Set to true only when the file is fully loaded.
169 * Used to prevent the premature generation of previews
170 * and by the citation inset.
172 bool file_fully_loaded;
175 mutable TocBackend toc_backend;
178 typedef pair<DocIterator, MacroData> ScopeMacro;
179 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
180 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
181 /// map from the macro name to the position map,
182 /// which maps the macro definition position to the scope and the MacroData.
183 NamePositionScopeMacroMap macros;
186 /// positions of child buffers in the buffer
187 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
188 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
189 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
190 /// position of children buffers in this buffer
191 BufferPositionMap children_positions;
192 /// map from children inclusion positions to their scope and their buffer
193 PositionScopeBufferMap position_to_children;
195 /// Container for all sort of Buffer dependant errors.
196 map<string, ErrorList> errorLists;
198 /// timestamp and checksum used to test if the file has been externally
199 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
201 unsigned long checksum_;
204 frontend::WorkAreaManager * wa_;
209 /// A cache for the bibfiles (including bibfiles of loaded child
210 /// documents), needed for appropriate update of natbib labels.
211 mutable support::FileNameList bibfilesCache_;
213 // FIXME The caching mechanism could be improved. At present, we have a
214 // cache for each Buffer, that caches all the bibliography info for that
215 // Buffer. A more efficient solution would be to have a global cache per
216 // file, and then to construct the Buffer's bibinfo from that.
217 /// A cache for bibliography info
218 mutable BiblioInfo bibinfo_;
219 /// whether the bibinfo cache is valid
220 bool bibinfoCacheValid_;
221 /// Cache of timestamps of .bib files
222 map<FileName, time_t> bibfileStatus_;
224 mutable RefCache ref_cache_;
226 /// our Text that should be wrapped in an InsetText
231 /// Creates the per buffer temporary directory
232 static FileName createBufferTmpDir()
235 // We are in our own directory. Why bother to mangle name?
236 // In fact I wrote this code to circumvent a problematic behaviour
237 // (bug?) of EMX mkstemp().
238 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
239 convert<string>(count++));
241 if (!tmpfl.createDirectory(0777)) {
242 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
243 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
244 from_utf8(tmpfl.absFilename())));
250 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
251 : parent_buffer(0), lyx_clean(true), bak_clean(true), unnamed(false),
252 read_only(readonly_), filename(file), file_fully_loaded(false),
253 toc_backend(&parent), macro_lock(false), timestamp_(0),
254 checksum_(0), wa_(0), undo_(parent), bibinfoCacheValid_(false)
256 temppath = createBufferTmpDir();
257 lyxvc.setBuffer(&parent);
259 wa_ = new frontend::WorkAreaManager;
263 Buffer::Buffer(string const & file, bool readonly)
264 : d(new Impl(*this, FileName(file), readonly)), gui_(0)
266 LYXERR(Debug::INFO, "Buffer::Buffer()");
268 d->inset = new InsetText(*this);
269 d->inset->setAutoBreakRows(true);
270 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
276 LYXERR(Debug::INFO, "Buffer::~Buffer()");
277 // here the buffer should take care that it is
278 // saved properly, before it goes into the void.
280 // GuiView already destroyed
283 if (d->unnamed && d->filename.extension() == "internal") {
284 // No need to do additional cleanups for internal buffer.
289 // loop over children
290 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
291 Impl::BufferPositionMap::iterator end = d->children_positions.end();
292 for (; it != end; ++it) {
293 // The child buffer might have been closed already.
294 if (theBufferList().isLoaded(child))
295 theBufferList().releaseChild(this, const_cast<Buffer *>(it->first));
298 // clear references to children in macro tables
299 d->children_positions.clear();
300 d->position_to_children.clear();
302 if (!d->temppath.destroyDirectory()) {
303 Alert::warning(_("Could not remove temporary directory"),
304 bformat(_("Could not remove the temporary directory %1$s"),
305 from_utf8(d->temppath.absFilename())));
308 // Remove any previewed LaTeX snippets associated with this buffer.
309 thePreviews().removeLoader(*this);
315 void Buffer::changed() const
322 frontend::WorkAreaManager & Buffer::workAreaManager() const
324 LASSERT(d->wa_, /**/);
329 Text & Buffer::text() const
331 return d->inset->text();
335 Inset & Buffer::inset() const
341 BufferParams & Buffer::params()
347 BufferParams const & Buffer::params() const
353 ParagraphList & Buffer::paragraphs()
355 return text().paragraphs();
359 ParagraphList const & Buffer::paragraphs() const
361 return text().paragraphs();
365 LyXVC & Buffer::lyxvc()
371 LyXVC const & Buffer::lyxvc() const
377 string const Buffer::temppath() const
379 return d->temppath.absFilename();
383 TexRow & Buffer::texrow()
389 TexRow const & Buffer::texrow() const
395 TocBackend & Buffer::tocBackend() const
397 return d->toc_backend;
401 Undo & Buffer::undo()
407 string Buffer::latexName(bool const no_path) const
409 FileName latex_name = makeLatexName(d->filename);
410 return no_path ? latex_name.onlyFileName()
411 : latex_name.absFilename();
415 string Buffer::logName(LogType * type) const
417 string const filename = latexName(false);
419 if (filename.empty()) {
425 string const path = temppath();
427 FileName const fname(addName(temppath(),
428 onlyFilename(changeExtension(filename,
430 FileName const bname(
431 addName(path, onlyFilename(
432 changeExtension(filename,
433 formats.extension("literate") + ".out"))));
435 // If no Latex log or Build log is newer, show Build log
437 if (bname.exists() &&
438 (!fname.exists() || fname.lastModified() < bname.lastModified())) {
439 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
442 return bname.absFilename();
444 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
447 return fname.absFilename();
451 void Buffer::setReadonly(bool const flag)
453 if (d->read_only != flag) {
460 void Buffer::setFileName(string const & newfile)
462 d->filename = makeAbsPath(newfile);
463 setReadonly(d->filename.isReadOnly());
468 int Buffer::readHeader(Lexer & lex)
470 int unknown_tokens = 0;
472 int begin_header_line = -1;
474 // Initialize parameters that may be/go lacking in header:
475 params().branchlist().clear();
476 params().preamble.erase();
477 params().options.erase();
478 params().master.erase();
479 params().float_placement.erase();
480 params().paperwidth.erase();
481 params().paperheight.erase();
482 params().leftmargin.erase();
483 params().rightmargin.erase();
484 params().topmargin.erase();
485 params().bottommargin.erase();
486 params().headheight.erase();
487 params().headsep.erase();
488 params().footskip.erase();
489 params().columnsep.erase();
490 params().fontsCJK.erase();
491 params().listings_params.clear();
492 params().clearLayoutModules();
493 params().clearRemovedModules();
494 params().pdfoptions().clear();
496 for (int i = 0; i < 4; ++i) {
497 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
498 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
501 ErrorList & errorList = d->errorLists["Parse"];
510 if (token == "\\end_header")
514 if (token == "\\begin_header") {
515 begin_header_line = line;
519 LYXERR(Debug::PARSER, "Handling document header token: `"
522 string unknown = params().readToken(lex, token, d->filename.onlyPath());
523 if (!unknown.empty()) {
524 if (unknown[0] != '\\' && token == "\\textclass") {
525 Alert::warning(_("Unknown document class"),
526 bformat(_("Using the default document class, because the "
527 "class %1$s is unknown."), from_utf8(unknown)));
530 docstring const s = bformat(_("Unknown token: "
534 errorList.push_back(ErrorItem(_("Document header error"),
539 if (begin_header_line) {
540 docstring const s = _("\\begin_header is missing");
541 errorList.push_back(ErrorItem(_("Document header error"),
545 params().makeDocumentClass();
547 return unknown_tokens;
552 // changed to be public and have one parameter
553 // Returns true if "\end_document" is not read (Asger)
554 bool Buffer::readDocument(Lexer & lex)
556 ErrorList & errorList = d->errorLists["Parse"];
559 if (!lex.checkFor("\\begin_document")) {
560 docstring const s = _("\\begin_document is missing");
561 errorList.push_back(ErrorItem(_("Document header error"),
565 // we are reading in a brand new document
566 LASSERT(paragraphs().empty(), /**/);
570 if (params().outputChanges) {
571 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
572 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
573 LaTeXFeatures::isAvailable("xcolor");
575 if (!dvipost && !xcolorulem) {
576 Alert::warning(_("Changes not shown in LaTeX output"),
577 _("Changes will not be highlighted in LaTeX output, "
578 "because neither dvipost nor xcolor/ulem are installed.\n"
579 "Please install these packages or redefine "
580 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
581 } else if (!xcolorulem) {
582 Alert::warning(_("Changes not shown in LaTeX output"),
583 _("Changes will not be highlighted in LaTeX output "
584 "when using pdflatex, because xcolor and ulem are not installed.\n"
585 "Please install both packages or redefine "
586 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
590 if (!params().master.empty()) {
591 FileName const master_file = makeAbsPath(params().master,
592 onlyPath(absFileName()));
593 if (isLyXFilename(master_file.absFilename())) {
595 checkAndLoadLyXFile(master_file, true);
597 // set master as master buffer, but only
598 // if we are a real child
599 if (master->isChild(this))
601 // if the master is not fully loaded
602 // it is probably just loading this
603 // child. No warning needed then.
604 else if (master->isFullyLoaded())
605 LYXERR0("The master '"
607 << "' assigned to this document '"
609 << "' does not include "
610 "this document. Ignoring the master assignment.");
616 bool const res = text().read(*this, lex, errorList, d->inset);
619 updateMacroInstances();
624 // needed to insert the selection
625 void Buffer::insertStringAsLines(ParagraphList & pars,
626 pit_type & pit, pos_type & pos,
627 Font const & fn, docstring const & str, bool autobreakrows)
631 // insert the string, don't insert doublespace
632 bool space_inserted = true;
633 for (docstring::const_iterator cit = str.begin();
634 cit != str.end(); ++cit) {
635 Paragraph & par = pars[pit];
637 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
638 breakParagraph(params(), pars, pit, pos,
639 par.layout().isEnvironment());
642 space_inserted = true;
646 // do not insert consecutive spaces if !free_spacing
647 } else if ((*cit == ' ' || *cit == '\t') &&
648 space_inserted && !par.isFreeSpacing()) {
650 } else if (*cit == '\t') {
651 if (!par.isFreeSpacing()) {
652 // tabs are like spaces here
653 par.insertChar(pos, ' ', font, params().trackChanges);
655 space_inserted = true;
657 par.insertChar(pos, *cit, font, params().trackChanges);
659 space_inserted = true;
661 } else if (!isPrintable(*cit)) {
662 // Ignore unprintables
665 // just insert the character
666 par.insertChar(pos, *cit, font, params().trackChanges);
668 space_inserted = (*cit == ' ');
675 bool Buffer::readString(string const & s)
677 params().compressed = false;
679 // remove dummy empty par
680 paragraphs().clear();
684 FileName const name = FileName::tempName("Buffer_readString");
685 switch (readFile(lex, name, true)) {
689 // We need to call lyx2lyx, so write the input to a file
690 ofstream os(name.toFilesystemEncoding().c_str());
693 return readFile(name);
703 bool Buffer::readFile(FileName const & filename)
705 FileName fname(filename);
707 params().compressed = fname.isZippedFile();
709 // remove dummy empty par
710 paragraphs().clear();
713 if (readFile(lex, fname) != success)
720 bool Buffer::isFullyLoaded() const
722 return d->file_fully_loaded;
726 void Buffer::setFullyLoaded(bool value)
728 d->file_fully_loaded = value;
732 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
735 LASSERT(!filename.empty(), /**/);
737 // the first (non-comment) token _must_ be...
738 if (!lex.checkFor("\\lyxformat")) {
739 Alert::error(_("Document format failure"),
740 bformat(_("%1$s is not a readable LyX document."),
741 from_utf8(filename.absFilename())));
747 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
748 // if present remove ".," from string.
749 size_t dot = tmp_format.find_first_of(".,");
750 //lyxerr << " dot found at " << dot << endl;
751 if (dot != string::npos)
752 tmp_format.erase(dot, 1);
753 int const file_format = convert<int>(tmp_format);
754 //lyxerr << "format: " << file_format << endl;
756 // save timestamp and checksum of the original disk file, making sure
757 // to not overwrite them with those of the file created in the tempdir
758 // when it has to be converted to the current format.
760 // Save the timestamp and checksum of disk file. If filename is an
761 // emergency file, save the timestamp and checksum of the original lyx file
762 // because isExternallyModified will check for this file. (BUG4193)
763 string diskfile = filename.absFilename();
764 if (suffixIs(diskfile, ".emergency"))
765 diskfile = diskfile.substr(0, diskfile.size() - 10);
766 saveCheckSum(FileName(diskfile));
769 if (file_format != LYX_FORMAT) {
772 // lyx2lyx would fail
775 FileName const tmpfile = FileName::tempName("Buffer_readFile");
776 if (tmpfile.empty()) {
777 Alert::error(_("Conversion failed"),
778 bformat(_("%1$s is from a different"
779 " version of LyX, but a temporary"
780 " file for converting it could"
782 from_utf8(filename.absFilename())));
785 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
786 if (lyx2lyx.empty()) {
787 Alert::error(_("Conversion script not found"),
788 bformat(_("%1$s is from a different"
789 " version of LyX, but the"
790 " conversion script lyx2lyx"
791 " could not be found."),
792 from_utf8(filename.absFilename())));
795 ostringstream command;
796 command << os::python()
797 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
798 << " -t " << convert<string>(LYX_FORMAT)
799 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
800 << ' ' << quoteName(filename.toFilesystemEncoding());
801 string const command_str = command.str();
803 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
805 cmd_ret const ret = runCommand(command_str);
806 if (ret.first != 0) {
807 Alert::error(_("Conversion script failed"),
808 bformat(_("%1$s is from a different version"
809 " of LyX, but the lyx2lyx script"
810 " failed to convert it."),
811 from_utf8(filename.absFilename())));
814 bool const ret = readFile(tmpfile);
815 // Do stuff with tmpfile name and buffer name here.
816 return ret ? success : failure;
821 if (readDocument(lex)) {
822 Alert::error(_("Document format failure"),
823 bformat(_("%1$s ended unexpectedly, which means"
824 " that it is probably corrupted."),
825 from_utf8(filename.absFilename())));
828 d->file_fully_loaded = true;
833 // Should probably be moved to somewhere else: BufferView? LyXView?
834 bool Buffer::save() const
836 // We don't need autosaves in the immediate future. (Asger)
837 resetAutosaveTimers();
839 string const encodedFilename = d->filename.toFilesystemEncoding();
842 bool madeBackup = false;
844 // make a backup if the file already exists
845 if (lyxrc.make_backup && fileName().exists()) {
846 backupName = FileName(absFileName() + '~');
847 if (!lyxrc.backupdir_path.empty()) {
848 string const mangledName =
849 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
850 backupName = FileName(addName(lyxrc.backupdir_path,
853 if (fileName().copyTo(backupName)) {
856 Alert::error(_("Backup failure"),
857 bformat(_("Cannot create backup file %1$s.\n"
858 "Please check whether the directory exists and is writeable."),
859 from_utf8(backupName.absFilename())));
860 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
864 // ask if the disk file has been externally modified (use checksum method)
865 if (fileName().exists() && isExternallyModified(checksum_method)) {
866 docstring const file = makeDisplayPath(absFileName(), 20);
867 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
868 "you want to overwrite this file?"), file);
869 int const ret = Alert::prompt(_("Overwrite modified file?"),
870 text, 1, 1, _("&Overwrite"), _("&Cancel"));
875 if (writeFile(d->filename)) {
879 // Saving failed, so backup is not backup
881 backupName.moveTo(d->filename);
887 bool Buffer::writeFile(FileName const & fname) const
889 if (d->read_only && fname == d->filename)
894 docstring const str = bformat(_("Saving document %1$s..."),
895 makeDisplayPath(fname.absFilename()));
898 if (params().compressed) {
899 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
900 retval = ofs && write(ofs);
902 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
903 retval = ofs && write(ofs);
907 message(str + _(" could not write file!"));
911 removeAutosaveFile(d->filename.absFilename());
913 saveCheckSum(d->filename);
914 message(str + _(" done."));
920 bool Buffer::write(ostream & ofs) const
923 // Use the standard "C" locale for file output.
924 ofs.imbue(locale::classic());
927 // The top of the file should not be written by params().
929 // write out a comment in the top of the file
930 ofs << "#LyX " << lyx_version
931 << " created this file. For more info see http://www.lyx.org/\n"
932 << "\\lyxformat " << LYX_FORMAT << "\n"
933 << "\\begin_document\n";
935 /// For each author, set 'used' to true if there is a change
936 /// by this author in the document; otherwise set it to 'false'.
937 AuthorList::Authors::const_iterator a_it = params().authors().begin();
938 AuthorList::Authors::const_iterator a_end = params().authors().end();
939 for (; a_it != a_end; ++a_it)
940 a_it->second.setUsed(false);
942 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
943 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
944 for ( ; it != end; ++it)
945 it->checkAuthors(params().authors());
947 // now write out the buffer parameters.
948 ofs << "\\begin_header\n";
949 params().writeFile(ofs);
950 ofs << "\\end_header\n";
953 ofs << "\n\\begin_body\n";
954 text().write(*this, ofs);
955 ofs << "\n\\end_body\n";
957 // Write marker that shows file is complete
958 ofs << "\\end_document" << endl;
960 // Shouldn't really be needed....
963 // how to check if close went ok?
964 // Following is an attempt... (BE 20001011)
966 // good() returns false if any error occured, including some
968 // bad() returns true if something bad happened in the buffer,
969 // which should include file system full errors.
974 lyxerr << "File was not closed properly." << endl;
981 bool Buffer::makeLaTeXFile(FileName const & fname,
982 string const & original_path,
983 OutputParams const & runparams,
984 bool output_preamble, bool output_body) const
986 string const encoding = runparams.encoding->iconvName();
987 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
990 try { ofs.reset(encoding); }
991 catch (iconv_codecvt_facet_exception & e) {
992 lyxerr << "Caught iconv exception: " << e.what() << endl;
993 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
994 "verify that the support software for your encoding (%1$s) is "
995 "properly installed"), from_ascii(encoding)));
998 if (!openFileWrite(ofs, fname))
1001 //TexStream ts(ofs.rdbuf(), &texrow());
1002 ErrorList & errorList = d->errorLists["Export"];
1004 bool failed_export = false;
1007 writeLaTeXSource(ofs, original_path,
1008 runparams, output_preamble, output_body);
1010 catch (EncodingException & e) {
1011 odocstringstream ods;
1012 ods.put(e.failed_char);
1014 oss << "0x" << hex << e.failed_char << dec;
1015 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1016 " (code point %2$s)"),
1017 ods.str(), from_utf8(oss.str()));
1018 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1019 "representable in the chosen encoding.\n"
1020 "Changing the document encoding to utf8 could help."),
1021 e.par_id, e.pos, e.pos + 1));
1022 failed_export = true;
1024 catch (iconv_codecvt_facet_exception & e) {
1025 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1026 _(e.what()), -1, 0, 0));
1027 failed_export = true;
1029 catch (exception const & e) {
1030 errorList.push_back(ErrorItem(_("conversion failed"),
1031 _(e.what()), -1, 0, 0));
1032 failed_export = true;
1035 lyxerr << "Caught some really weird exception..." << endl;
1041 failed_export = true;
1042 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1046 return !failed_export;
1050 void Buffer::writeLaTeXSource(odocstream & os,
1051 string const & original_path,
1052 OutputParams const & runparams_in,
1053 bool const output_preamble, bool const output_body) const
1055 // The child documents, if any, shall be already loaded at this point.
1057 OutputParams runparams = runparams_in;
1059 // Classify the unicode characters appearing in math insets
1060 Encodings::initUnicodeMath(*this);
1062 // validate the buffer.
1063 LYXERR(Debug::LATEX, " Validating buffer...");
1064 LaTeXFeatures features(*this, params(), runparams);
1066 LYXERR(Debug::LATEX, " Buffer validation done.");
1068 // The starting paragraph of the coming rows is the
1069 // first paragraph of the document. (Asger)
1070 if (output_preamble && runparams.nice) {
1071 os << "%% LyX " << lyx_version << " created this file. "
1072 "For more info, see http://www.lyx.org/.\n"
1073 "%% Do not edit unless you really know what "
1075 d->texrow.newline();
1076 d->texrow.newline();
1078 LYXERR(Debug::INFO, "lyx document header finished");
1080 // Don't move this behind the parent_buffer=0 code below,
1081 // because then the macros will not get the right "redefinition"
1082 // flag as they don't see the parent macros which are output before.
1085 // fold macros if possible, still with parent buffer as the
1086 // macros will be put in the prefix anyway.
1087 updateMacroInstances();
1089 // There are a few differences between nice LaTeX and usual files:
1090 // usual is \batchmode and has a
1091 // special input@path to allow the including of figures
1092 // with either \input or \includegraphics (what figinsets do).
1093 // input@path is set when the actual parameter
1094 // original_path is set. This is done for usual tex-file, but not
1095 // for nice-latex-file. (Matthias 250696)
1096 // Note that input@path is only needed for something the user does
1097 // in the preamble, included .tex files or ERT, files included by
1098 // LyX work without it.
1099 if (output_preamble) {
1100 if (!runparams.nice) {
1101 // code for usual, NOT nice-latex-file
1102 os << "\\batchmode\n"; // changed
1103 // from \nonstopmode
1104 d->texrow.newline();
1106 if (!original_path.empty()) {
1108 // We don't know the encoding of inputpath
1109 docstring const inputpath = from_utf8(latex_path(original_path));
1110 os << "\\makeatletter\n"
1111 << "\\def\\input@path{{"
1112 << inputpath << "/}}\n"
1113 << "\\makeatother\n";
1114 d->texrow.newline();
1115 d->texrow.newline();
1116 d->texrow.newline();
1119 // get parent macros (if this buffer has a parent) which will be
1120 // written at the document begin further down.
1121 MacroSet parentMacros;
1122 listParentMacros(parentMacros, features);
1124 // Write the preamble
1125 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1127 runparams.use_japanese = features.isRequired("japanese");
1133 os << "\\begin{document}\n";
1134 d->texrow.newline();
1136 // output the parent macros
1137 MacroSet::iterator it = parentMacros.begin();
1138 MacroSet::iterator end = parentMacros.end();
1139 for (; it != end; ++it)
1140 (*it)->write(os, true);
1141 } // output_preamble
1143 d->texrow.start(paragraphs().begin()->id(), 0);
1145 LYXERR(Debug::INFO, "preamble finished, now the body.");
1147 // if we are doing a real file with body, even if this is the
1148 // child of some other buffer, let's cut the link here.
1149 // This happens for example if only a child document is printed.
1150 Buffer const * save_parent = 0;
1151 if (output_preamble) {
1152 save_parent = d->parent_buffer;
1153 d->parent_buffer = 0;
1157 latexParagraphs(*this, text(), os, d->texrow, runparams);
1159 // Restore the parenthood if needed
1160 if (output_preamble)
1161 d->parent_buffer = save_parent;
1163 // add this just in case after all the paragraphs
1165 d->texrow.newline();
1167 if (output_preamble) {
1168 os << "\\end{document}\n";
1169 d->texrow.newline();
1170 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1172 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1174 runparams_in.encoding = runparams.encoding;
1176 // Just to be sure. (Asger)
1177 d->texrow.newline();
1179 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1180 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1184 bool Buffer::isLatex() const
1186 return params().documentClass().outputType() == LATEX;
1190 bool Buffer::isLiterate() const
1192 return params().documentClass().outputType() == LITERATE;
1196 bool Buffer::isDocBook() const
1198 return params().documentClass().outputType() == DOCBOOK;
1202 void Buffer::makeDocBookFile(FileName const & fname,
1203 OutputParams const & runparams,
1204 bool const body_only) const
1206 LYXERR(Debug::LATEX, "makeDocBookFile...");
1209 if (!openFileWrite(ofs, fname))
1212 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1216 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1220 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1221 OutputParams const & runparams,
1222 bool const only_body) const
1224 LaTeXFeatures features(*this, params(), runparams);
1229 DocumentClass const & tclass = params().documentClass();
1230 string const top_element = tclass.latexname();
1233 if (runparams.flavor == OutputParams::XML)
1234 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1237 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1240 if (! tclass.class_header().empty())
1241 os << from_ascii(tclass.class_header());
1242 else if (runparams.flavor == OutputParams::XML)
1243 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1244 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1246 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1248 docstring preamble = from_utf8(params().preamble);
1249 if (runparams.flavor != OutputParams::XML ) {
1250 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1251 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1252 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1253 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1256 string const name = runparams.nice
1257 ? changeExtension(absFileName(), ".sgml") : fname;
1258 preamble += features.getIncludedFiles(name);
1259 preamble += features.getLyXSGMLEntities();
1261 if (!preamble.empty()) {
1262 os << "\n [ " << preamble << " ]";
1267 string top = top_element;
1269 if (runparams.flavor == OutputParams::XML)
1270 top += params().language->code();
1272 top += params().language->code().substr(0, 2);
1275 if (!params().options.empty()) {
1277 top += params().options;
1280 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1281 << " file was created by LyX " << lyx_version
1282 << "\n See http://www.lyx.org/ for more information -->\n";
1284 params().documentClass().counters().reset();
1288 sgml::openTag(os, top);
1290 docbookParagraphs(paragraphs(), *this, os, runparams);
1291 sgml::closeTag(os, top_element);
1295 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1296 // Other flags: -wall -v0 -x
1297 int Buffer::runChktex()
1301 // get LaTeX-Filename
1302 FileName const path(temppath());
1303 string const name = addName(path.absFilename(), latexName());
1304 string const org_path = filePath();
1306 PathChanger p(path); // path to LaTeX file
1307 message(_("Running chktex..."));
1309 // Generate the LaTeX file if neccessary
1310 OutputParams runparams(¶ms().encoding());
1311 runparams.flavor = OutputParams::LATEX;
1312 runparams.nice = false;
1313 makeLaTeXFile(FileName(name), org_path, runparams);
1316 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1317 int const res = chktex.run(terr); // run chktex
1320 Alert::error(_("chktex failure"),
1321 _("Could not run chktex successfully."));
1322 } else if (res > 0) {
1323 ErrorList & errlist = d->errorLists["ChkTeX"];
1325 bufferErrors(terr, errlist);
1336 void Buffer::validate(LaTeXFeatures & features) const
1338 params().validate(features);
1342 for_each(paragraphs().begin(), paragraphs().end(),
1343 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1345 if (lyxerr.debugging(Debug::LATEX)) {
1346 features.showStruct();
1351 void Buffer::getLabelList(vector<docstring> & list) const
1353 // If this is a child document, use the parent's list instead.
1354 if (d->parent_buffer) {
1355 d->parent_buffer->getLabelList(list);
1360 Toc & toc = d->toc_backend.toc("label");
1361 TocIterator toc_it = toc.begin();
1362 TocIterator end = toc.end();
1363 for (; toc_it != end; ++toc_it) {
1364 if (toc_it->depth() == 0)
1365 list.push_back(toc_it->str());
1370 void Buffer::updateBibfilesCache() const
1372 // If this is a child document, use the parent's cache instead.
1373 if (d->parent_buffer) {
1374 d->parent_buffer->updateBibfilesCache();
1378 d->bibfilesCache_.clear();
1379 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1380 if (it->lyxCode() == BIBTEX_CODE) {
1381 InsetBibtex const & inset =
1382 static_cast<InsetBibtex const &>(*it);
1383 support::FileNameList const bibfiles = inset.getBibFiles();
1384 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1387 } else if (it->lyxCode() == INCLUDE_CODE) {
1388 InsetInclude & inset =
1389 static_cast<InsetInclude &>(*it);
1390 inset.updateBibfilesCache();
1391 support::FileNameList const & bibfiles =
1392 inset.getBibfilesCache(*this);
1393 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1398 // the bibinfo cache is now invalid
1399 d->bibinfoCacheValid_ = false;
1403 void Buffer::invalidateBibinfoCache()
1405 d->bibinfoCacheValid_ = false;
1409 support::FileNameList const & Buffer::getBibfilesCache() const
1411 // If this is a child document, use the parent's cache instead.
1412 if (d->parent_buffer)
1413 return d->parent_buffer->getBibfilesCache();
1415 // We update the cache when first used instead of at loading time.
1416 if (d->bibfilesCache_.empty())
1417 const_cast<Buffer *>(this)->updateBibfilesCache();
1419 return d->bibfilesCache_;
1423 BiblioInfo const & Buffer::masterBibInfo() const
1425 // if this is a child document and the parent is already loaded
1426 // use the parent's list instead [ale990412]
1427 Buffer const * const tmp = masterBuffer();
1430 return tmp->masterBibInfo();
1431 return localBibInfo();
1435 BiblioInfo const & Buffer::localBibInfo() const
1437 if (d->bibinfoCacheValid_) {
1438 support::FileNameList const & bibfilesCache = getBibfilesCache();
1439 // compare the cached timestamps with the actual ones.
1440 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1441 support::FileNameList::const_iterator en = bibfilesCache.end();
1442 for (; ei != en; ++ ei) {
1443 time_t lastw = ei->lastModified();
1444 if (lastw != d->bibfileStatus_[*ei]) {
1445 d->bibinfoCacheValid_ = false;
1446 d->bibfileStatus_[*ei] = lastw;
1452 if (!d->bibinfoCacheValid_) {
1453 d->bibinfo_.clear();
1454 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1455 it->fillWithBibKeys(d->bibinfo_, it);
1456 d->bibinfoCacheValid_ = true;
1462 bool Buffer::isDepClean(string const & name) const
1464 DepClean::const_iterator const it = d->dep_clean.find(name);
1465 if (it == d->dep_clean.end())
1471 void Buffer::markDepClean(string const & name)
1473 d->dep_clean[name] = true;
1477 bool Buffer::dispatch(string const & command, bool * result)
1479 return dispatch(lyxaction.lookupFunc(command), result);
1483 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1485 bool dispatched = true;
1487 switch (func.action) {
1488 case LFUN_BUFFER_EXPORT: {
1489 bool const tmp = doExport(to_utf8(func.argument()), false);
1495 case LFUN_BRANCH_ACTIVATE:
1496 case LFUN_BRANCH_DEACTIVATE: {
1497 BranchList & branchList = params().branchlist();
1498 docstring const branchName = func.argument();
1499 Branch * branch = branchList.find(branchName);
1501 LYXERR0("Branch " << branchName << " does not exist.");
1503 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1515 void Buffer::changeLanguage(Language const * from, Language const * to)
1517 LASSERT(from, /**/);
1520 for_each(par_iterator_begin(),
1522 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1526 bool Buffer::isMultiLingual() const
1528 ParConstIterator end = par_iterator_end();
1529 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1530 if (it->isMultiLingual(params()))
1537 DocIterator Buffer::getParFromID(int const id) const
1539 Buffer * buf = const_cast<Buffer *>(this);
1541 // John says this is called with id == -1 from undo
1542 lyxerr << "getParFromID(), id: " << id << endl;
1543 return doc_iterator_end(buf);
1546 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
1547 if (it.paragraph().id() == id)
1550 return doc_iterator_end(buf);
1554 bool Buffer::hasParWithID(int const id) const
1556 return !getParFromID(id).atEnd();
1560 ParIterator Buffer::par_iterator_begin()
1562 return ParIterator(doc_iterator_begin(this));
1566 ParIterator Buffer::par_iterator_end()
1568 return ParIterator(doc_iterator_end(this));
1572 ParConstIterator Buffer::par_iterator_begin() const
1574 return ParConstIterator(doc_iterator_begin(this));
1578 ParConstIterator Buffer::par_iterator_end() const
1580 return ParConstIterator(doc_iterator_end(this));
1584 Language const * Buffer::language() const
1586 return params().language;
1590 docstring const Buffer::B_(string const & l10n) const
1592 return params().B_(l10n);
1596 bool Buffer::isClean() const
1598 return d->lyx_clean;
1602 bool Buffer::isBakClean() const
1604 return d->bak_clean;
1608 bool Buffer::isExternallyModified(CheckMethod method) const
1610 LASSERT(d->filename.exists(), /**/);
1611 // if method == timestamp, check timestamp before checksum
1612 return (method == checksum_method
1613 || d->timestamp_ != d->filename.lastModified())
1614 && d->checksum_ != d->filename.checksum();
1618 void Buffer::saveCheckSum(FileName const & file) const
1620 if (file.exists()) {
1621 d->timestamp_ = file.lastModified();
1622 d->checksum_ = file.checksum();
1624 // in the case of save to a new file.
1631 void Buffer::markClean() const
1633 if (!d->lyx_clean) {
1634 d->lyx_clean = true;
1637 // if the .lyx file has been saved, we don't need an
1639 d->bak_clean = true;
1643 void Buffer::markBakClean() const
1645 d->bak_clean = true;
1649 void Buffer::setUnnamed(bool flag)
1655 bool Buffer::isUnnamed() const
1661 // FIXME: this function should be moved to buffer_pimpl.C
1662 void Buffer::markDirty()
1665 d->lyx_clean = false;
1668 d->bak_clean = false;
1670 DepClean::iterator it = d->dep_clean.begin();
1671 DepClean::const_iterator const end = d->dep_clean.end();
1673 for (; it != end; ++it)
1678 FileName Buffer::fileName() const
1684 string Buffer::absFileName() const
1686 return d->filename.absFilename();
1690 string Buffer::filePath() const
1692 return d->filename.onlyPath().absFilename() + "/";
1696 bool Buffer::isReadonly() const
1698 return d->read_only;
1702 void Buffer::setParent(Buffer const * buffer)
1704 // Avoids recursive include.
1705 d->parent_buffer = buffer == this ? 0 : buffer;
1710 Buffer const * Buffer::parent() const
1712 return d->parent_buffer;
1716 void Buffer::collectRelatives(BufferSet & bufs) const
1720 parent()->collectRelatives(bufs);
1722 // loop over children
1723 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
1724 Impl::BufferPositionMap::iterator end = d->children_positions.end();
1725 for (; it != end; ++it)
1726 bufs.insert(const_cast<Buffer *>(it->first));
1730 std::vector<Buffer const *> Buffer::allRelatives() const
1733 collectRelatives(bufs);
1734 BufferSet::iterator it = bufs.begin();
1735 std::vector<Buffer const *> ret;
1736 for (; it != bufs.end(); ++it)
1742 Buffer const * Buffer::masterBuffer() const
1744 if (!d->parent_buffer)
1747 return d->parent_buffer->masterBuffer();
1751 bool Buffer::isChild(Buffer * child) const
1753 return d->children_positions.find(child) != d->children_positions.end();
1757 DocIterator Buffer::firstChildPosition(Buffer const * child)
1759 Impl::BufferPositionMap::iterator it;
1760 it = d->children_positions.find(child);
1761 if (it == d->children_positions.end())
1762 return DocIterator(this);
1767 template<typename M>
1768 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
1773 typename M::iterator it = m.lower_bound(x);
1774 if (it == m.begin())
1782 MacroData const * Buffer::getBufferMacro(docstring const & name,
1783 DocIterator const & pos) const
1785 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
1787 // if paragraphs have no macro context set, pos will be empty
1791 // we haven't found anything yet
1792 DocIterator bestPos = par_iterator_begin();
1793 MacroData const * bestData = 0;
1795 // find macro definitions for name
1796 Impl::NamePositionScopeMacroMap::iterator nameIt
1797 = d->macros.find(name);
1798 if (nameIt != d->macros.end()) {
1799 // find last definition in front of pos or at pos itself
1800 Impl::PositionScopeMacroMap::const_iterator it
1801 = greatest_below(nameIt->second, pos);
1802 if (it != nameIt->second.end()) {
1804 // scope ends behind pos?
1805 if (pos < it->second.first) {
1806 // Looks good, remember this. If there
1807 // is no external macro behind this,
1808 // we found the right one already.
1809 bestPos = it->first;
1810 bestData = &it->second.second;
1814 // try previous macro if there is one
1815 if (it == nameIt->second.begin())
1822 // find macros in included files
1823 Impl::PositionScopeBufferMap::const_iterator it
1824 = greatest_below(d->position_to_children, pos);
1825 if (it == d->position_to_children.end())
1826 // no children before
1830 // do we know something better (i.e. later) already?
1831 if (it->first < bestPos )
1834 // scope ends behind pos?
1835 if (pos < it->second.first) {
1836 // look for macro in external file
1837 d->macro_lock = true;
1838 MacroData const * data
1839 = it->second.second->getMacro(name, false);
1840 d->macro_lock = false;
1842 bestPos = it->first;
1848 // try previous file if there is one
1849 if (it == d->position_to_children.begin())
1854 // return the best macro we have found
1859 MacroData const * Buffer::getMacro(docstring const & name,
1860 DocIterator const & pos, bool global) const
1865 // query buffer macros
1866 MacroData const * data = getBufferMacro(name, pos);
1870 // If there is a master buffer, query that
1871 if (d->parent_buffer) {
1872 d->macro_lock = true;
1873 MacroData const * macro = d->parent_buffer->getMacro(
1874 name, *this, false);
1875 d->macro_lock = false;
1881 data = MacroTable::globalMacros().get(name);
1890 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
1892 // set scope end behind the last paragraph
1893 DocIterator scope = par_iterator_begin();
1894 scope.pit() = scope.lastpit() + 1;
1896 return getMacro(name, scope, global);
1900 MacroData const * Buffer::getMacro(docstring const & name,
1901 Buffer const & child, bool global) const
1903 // look where the child buffer is included first
1904 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
1905 if (it == d->children_positions.end())
1908 // check for macros at the inclusion position
1909 return getMacro(name, it->second, global);
1913 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
1915 pit_type lastpit = it.lastpit();
1917 // look for macros in each paragraph
1918 while (it.pit() <= lastpit) {
1919 Paragraph & par = it.paragraph();
1921 // iterate over the insets of the current paragraph
1922 InsetList const & insets = par.insetList();
1923 InsetList::const_iterator iit = insets.begin();
1924 InsetList::const_iterator end = insets.end();
1925 for (; iit != end; ++iit) {
1926 it.pos() = iit->pos;
1928 // is it a nested text inset?
1929 if (iit->inset->asInsetText()) {
1930 // Inset needs its own scope?
1931 InsetText const * itext
1932 = iit->inset->asInsetText();
1933 bool newScope = itext->isMacroScope();
1935 // scope which ends just behind the inset
1936 DocIterator insetScope = it;
1939 // collect macros in inset
1940 it.push_back(CursorSlice(*iit->inset));
1941 updateMacros(it, newScope ? insetScope : scope);
1946 // is it an external file?
1947 if (iit->inset->lyxCode() == INCLUDE_CODE) {
1948 // get buffer of external file
1949 InsetInclude const & inset
1950 = static_cast<InsetInclude const &>(*iit->inset);
1951 d->macro_lock = true;
1952 Buffer * child = inset.loadIfNeeded(*this);
1953 d->macro_lock = false;
1957 // register its position, but only when it is
1958 // included first in the buffer
1959 if (d->children_positions.find(child)
1960 == d->children_positions.end())
1961 d->children_positions[child] = it;
1963 // register child with its scope
1964 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
1968 if (iit->inset->lyxCode() != MATHMACRO_CODE)
1972 MathMacroTemplate & macroTemplate
1973 = static_cast<MathMacroTemplate &>(*iit->inset);
1974 MacroContext mc(*this, it);
1975 macroTemplate.updateToContext(mc);
1978 bool valid = macroTemplate.validMacro();
1979 // FIXME: Should be fixNameAndCheckIfValid() in fact,
1980 // then the BufferView's cursor will be invalid in
1981 // some cases which leads to crashes.
1986 d->macros[macroTemplate.name()][it] =
1987 Impl::ScopeMacro(scope, MacroData(*this, it));
1997 void Buffer::updateMacros() const
2002 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2004 // start with empty table
2006 d->children_positions.clear();
2007 d->position_to_children.clear();
2009 // Iterate over buffer, starting with first paragraph
2010 // The scope must be bigger than any lookup DocIterator
2011 // later. For the global lookup, lastpit+1 is used, hence
2012 // we use lastpit+2 here.
2013 DocIterator it = par_iterator_begin();
2014 DocIterator outerScope = it;
2015 outerScope.pit() = outerScope.lastpit() + 2;
2016 updateMacros(it, outerScope);
2020 void Buffer::updateMacroInstances() const
2022 LYXERR(Debug::MACROS, "updateMacroInstances for "
2023 << d->filename.onlyFileName());
2024 DocIterator it = doc_iterator_begin(this);
2025 DocIterator end = doc_iterator_end(this);
2026 for (; it != end; it.forwardPos()) {
2027 // look for MathData cells in InsetMathNest insets
2028 Inset * inset = it.nextInset();
2032 InsetMath * minset = inset->asInsetMath();
2036 // update macro in all cells of the InsetMathNest
2037 DocIterator::idx_type n = minset->nargs();
2038 MacroContext mc = MacroContext(*this, it);
2039 for (DocIterator::idx_type i = 0; i < n; ++i) {
2040 MathData & data = minset->cell(i);
2041 data.updateMacros(0, mc);
2047 void Buffer::listMacroNames(MacroNameSet & macros) const
2052 d->macro_lock = true;
2054 // loop over macro names
2055 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2056 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2057 for (; nameIt != nameEnd; ++nameIt)
2058 macros.insert(nameIt->first);
2060 // loop over children
2061 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2062 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2063 for (; it != end; ++it)
2064 it->first->listMacroNames(macros);
2067 if (d->parent_buffer)
2068 d->parent_buffer->listMacroNames(macros);
2070 d->macro_lock = false;
2074 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2076 if (!d->parent_buffer)
2080 d->parent_buffer->listMacroNames(names);
2083 MacroNameSet::iterator it = names.begin();
2084 MacroNameSet::iterator end = names.end();
2085 for (; it != end; ++it) {
2087 MacroData const * data =
2088 d->parent_buffer->getMacro(*it, *this, false);
2090 macros.insert(data);
2092 // we cannot access the original MathMacroTemplate anymore
2093 // here to calls validate method. So we do its work here manually.
2094 // FIXME: somehow make the template accessible here.
2095 if (data->optionals() > 0)
2096 features.require("xargs");
2102 Buffer::References & Buffer::references(docstring const & label)
2104 if (d->parent_buffer)
2105 return const_cast<Buffer *>(masterBuffer())->references(label);
2107 RefCache::iterator it = d->ref_cache_.find(label);
2108 if (it != d->ref_cache_.end())
2109 return it->second.second;
2111 static InsetLabel const * dummy_il = 0;
2112 static References const dummy_refs;
2113 it = d->ref_cache_.insert(
2114 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2115 return it->second.second;
2119 Buffer::References const & Buffer::references(docstring const & label) const
2121 return const_cast<Buffer *>(this)->references(label);
2125 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2127 masterBuffer()->d->ref_cache_[label].first = il;
2131 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2133 return masterBuffer()->d->ref_cache_[label].first;
2137 void Buffer::clearReferenceCache() const
2139 if (!d->parent_buffer)
2140 d->ref_cache_.clear();
2144 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2147 //FIXME: This does not work for child documents yet.
2148 LASSERT(code == CITE_CODE, /**/);
2149 // Check if the label 'from' appears more than once
2150 vector<docstring> labels;
2152 BiblioInfo const & keys = masterBibInfo();
2153 BiblioInfo::const_iterator bit = keys.begin();
2154 BiblioInfo::const_iterator bend = keys.end();
2156 for (; bit != bend; ++bit)
2158 labels.push_back(bit->first);
2161 if (count(labels.begin(), labels.end(), from) > 1)
2164 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2165 if (it->lyxCode() == code) {
2166 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2167 docstring const oldValue = inset.getParam(paramName);
2168 if (oldValue == from)
2169 inset.setParam(paramName, to);
2175 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2176 pit_type par_end, bool full_source) const
2178 OutputParams runparams(¶ms().encoding());
2179 runparams.nice = true;
2180 runparams.flavor = OutputParams::LATEX;
2181 runparams.linelen = lyxrc.plaintext_linelen;
2182 // No side effect of file copying and image conversion
2183 runparams.dryrun = true;
2187 os << "% " << _("Preview source code") << "\n\n";
2188 d->texrow.newline();
2189 d->texrow.newline();
2191 writeDocBookSource(os, absFileName(), runparams, false);
2193 // latex or literate
2194 writeLaTeXSource(os, string(), runparams, true, true);
2196 runparams.par_begin = par_begin;
2197 runparams.par_end = par_end;
2198 if (par_begin + 1 == par_end) {
2200 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2204 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2205 convert<docstring>(par_begin),
2206 convert<docstring>(par_end - 1))
2209 d->texrow.newline();
2210 d->texrow.newline();
2211 // output paragraphs
2213 docbookParagraphs(paragraphs(), *this, os, runparams);
2215 // latex or literate
2216 latexParagraphs(*this, text(), os, d->texrow, runparams);
2221 ErrorList & Buffer::errorList(string const & type) const
2223 static ErrorList emptyErrorList;
2224 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2225 if (I == d->errorLists.end())
2226 return emptyErrorList;
2232 void Buffer::updateTocItem(std::string const & type,
2233 DocIterator const & dit) const
2236 gui_->updateTocItem(type, dit);
2240 void Buffer::structureChanged() const
2243 gui_->structureChanged();
2247 void Buffer::errors(string const & err) const
2254 void Buffer::message(docstring const & msg) const
2261 void Buffer::setBusy(bool on) const
2268 void Buffer::setReadOnly(bool on) const
2271 d->wa_->setReadOnly(on);
2275 void Buffer::updateTitles() const
2278 d->wa_->updateTitles();
2282 void Buffer::resetAutosaveTimers() const
2285 gui_->resetAutosaveTimers();
2289 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2298 class AutoSaveBuffer : public ForkedProcess {
2301 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2302 : buffer_(buffer), fname_(fname) {}
2304 virtual boost::shared_ptr<ForkedProcess> clone() const
2306 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2311 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2312 from_utf8(fname_.absFilename())));
2313 return run(DontWait);
2317 virtual int generateChild();
2319 Buffer const & buffer_;
2324 int AutoSaveBuffer::generateChild()
2326 // tmp_ret will be located (usually) in /tmp
2327 // will that be a problem?
2328 // Note that this calls ForkedCalls::fork(), so it's
2329 // ok cross-platform.
2330 pid_t const pid = fork();
2331 // If you want to debug the autosave
2332 // you should set pid to -1, and comment out the fork.
2333 if (pid != 0 && pid != -1)
2336 // pid = -1 signifies that lyx was unable
2337 // to fork. But we will do the save
2339 bool failed = false;
2340 FileName const tmp_ret = FileName::tempName("lyxauto");
2341 if (!tmp_ret.empty()) {
2342 buffer_.writeFile(tmp_ret);
2343 // assume successful write of tmp_ret
2344 if (!tmp_ret.moveTo(fname_))
2350 // failed to write/rename tmp_ret so try writing direct
2351 if (!buffer_.writeFile(fname_)) {
2352 // It is dangerous to do this in the child,
2353 // but safe in the parent, so...
2354 if (pid == -1) // emit message signal.
2355 buffer_.message(_("Autosave failed!"));
2359 if (pid == 0) // we are the child so...
2368 // Perfect target for a thread...
2369 void Buffer::autoSave() const
2371 if (isBakClean() || isReadonly()) {
2372 // We don't save now, but we'll try again later
2373 resetAutosaveTimers();
2377 // emit message signal.
2378 message(_("Autosaving current document..."));
2380 // create autosave filename
2381 string fname = filePath();
2383 fname += d->filename.onlyFileName();
2386 AutoSaveBuffer autosave(*this, FileName(fname));
2390 resetAutosaveTimers();
2394 string Buffer::bufferFormat() const
2400 if (params().encoding().package() == Encoding::japanese)
2406 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2407 string & result_file) const
2409 string backend_format;
2410 OutputParams runparams(¶ms().encoding());
2411 runparams.flavor = OutputParams::LATEX;
2412 runparams.linelen = lyxrc.plaintext_linelen;
2413 vector<string> backs = backends();
2414 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2415 // Get shortest path to format
2416 Graph::EdgePath path;
2417 for (vector<string>::const_iterator it = backs.begin();
2418 it != backs.end(); ++it) {
2419 Graph::EdgePath p = theConverters().getPath(*it, format);
2420 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2421 backend_format = *it;
2426 runparams.flavor = theConverters().getFlavor(path);
2428 Alert::error(_("Couldn't export file"),
2429 bformat(_("No information for exporting the format %1$s."),
2430 formats.prettyName(format)));
2434 backend_format = format;
2435 // FIXME: Don't hardcode format names here, but use a flag
2436 if (backend_format == "pdflatex")
2437 runparams.flavor = OutputParams::PDFLATEX;
2440 string filename = latexName(false);
2441 filename = addName(temppath(), filename);
2442 filename = changeExtension(filename,
2443 formats.extension(backend_format));
2446 updateMacroInstances();
2448 // Plain text backend
2449 if (backend_format == "text")
2450 writePlaintextFile(*this, FileName(filename), runparams);
2452 else if (backend_format == "lyx")
2453 writeFile(FileName(filename));
2455 else if (isDocBook()) {
2456 runparams.nice = !put_in_tempdir;
2457 makeDocBookFile(FileName(filename), runparams);
2460 else if (backend_format == format) {
2461 runparams.nice = true;
2462 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2464 } else if (!lyxrc.tex_allows_spaces
2465 && contains(filePath(), ' ')) {
2466 Alert::error(_("File name error"),
2467 _("The directory path to the document cannot contain spaces."));
2470 runparams.nice = false;
2471 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2475 string const error_type = (format == "program")
2476 ? "Build" : bufferFormat();
2477 ErrorList & error_list = d->errorLists[error_type];
2478 string const ext = formats.extension(format);
2479 FileName const tmp_result_file(changeExtension(filename, ext));
2480 bool const success = theConverters().convert(this, FileName(filename),
2481 tmp_result_file, FileName(absFileName()), backend_format, format,
2483 // Emit the signal to show the error list.
2484 if (format != backend_format)
2489 if (put_in_tempdir) {
2490 result_file = tmp_result_file.absFilename();
2494 result_file = changeExtension(absFileName(), ext);
2495 // We need to copy referenced files (e. g. included graphics
2496 // if format == "dvi") to the result dir.
2497 vector<ExportedFile> const files =
2498 runparams.exportdata->externalFiles(format);
2499 string const dest = onlyPath(result_file);
2500 CopyStatus status = SUCCESS;
2501 for (vector<ExportedFile>::const_iterator it = files.begin();
2502 it != files.end() && status != CANCEL; ++it) {
2503 string const fmt = formats.getFormatFromFile(it->sourceName);
2504 status = copyFile(fmt, it->sourceName,
2505 makeAbsPath(it->exportName, dest),
2506 it->exportName, status == FORCE);
2508 if (status == CANCEL) {
2509 message(_("Document export cancelled."));
2510 } else if (tmp_result_file.exists()) {
2511 // Finally copy the main file
2512 status = copyFile(format, tmp_result_file,
2513 FileName(result_file), result_file,
2515 message(bformat(_("Document exported as %1$s "
2517 formats.prettyName(format),
2518 makeDisplayPath(result_file)));
2520 // This must be a dummy converter like fax (bug 1888)
2521 message(bformat(_("Document exported as %1$s"),
2522 formats.prettyName(format)));
2529 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2532 return doExport(format, put_in_tempdir, result_file);
2536 bool Buffer::preview(string const & format) const
2539 if (!doExport(format, true, result_file))
2541 return formats.view(*this, FileName(result_file), format);
2545 bool Buffer::isExportable(string const & format) const
2547 vector<string> backs = backends();
2548 for (vector<string>::const_iterator it = backs.begin();
2549 it != backs.end(); ++it)
2550 if (theConverters().isReachable(*it, format))
2556 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2558 vector<string> backs = backends();
2559 vector<Format const *> result =
2560 theConverters().getReachable(backs[0], only_viewable, true);
2561 for (vector<string>::const_iterator it = backs.begin() + 1;
2562 it != backs.end(); ++it) {
2563 vector<Format const *> r =
2564 theConverters().getReachable(*it, only_viewable, false);
2565 result.insert(result.end(), r.begin(), r.end());
2571 vector<string> Buffer::backends() const
2574 if (params().baseClass()->isTeXClassAvailable()) {
2575 v.push_back(bufferFormat());
2576 // FIXME: Don't hardcode format names here, but use a flag
2577 if (v.back() == "latex")
2578 v.push_back("pdflatex");
2580 v.push_back("text");
2586 bool Buffer::readFileHelper(FileName const & s)
2588 // File information about normal file
2590 docstring const file = makeDisplayPath(s.absFilename(), 50);
2591 docstring text = bformat(_("The specified document\n%1$s"
2592 "\ncould not be read."), file);
2593 Alert::error(_("Could not read document"), text);
2597 // Check if emergency save file exists and is newer.
2598 FileName const e(s.absFilename() + ".emergency");
2600 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2601 docstring const file = makeDisplayPath(s.absFilename(), 20);
2602 docstring const text =
2603 bformat(_("An emergency save of the document "
2605 "Recover emergency save?"), file);
2606 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2607 _("&Recover"), _("&Load Original"),
2611 // the file is not saved if we load the emergency file.
2621 // Now check if autosave file is newer.
2622 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2624 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2625 docstring const file = makeDisplayPath(s.absFilename(), 20);
2626 docstring const text =
2627 bformat(_("The backup of the document "
2628 "%1$s is newer.\n\nLoad the "
2629 "backup instead?"), file);
2630 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2631 _("&Load backup"), _("Load &original"),
2635 // the file is not saved if we load the autosave file.
2639 // Here we delete the autosave
2650 bool Buffer::loadLyXFile(FileName const & s)
2652 if (s.isReadableFile()) {
2653 if (readFileHelper(s)) {
2654 lyxvc().file_found_hook(s);
2655 if (!s.isWritable())
2660 docstring const file = makeDisplayPath(s.absFilename(), 20);
2661 // Here we probably should run
2662 if (LyXVC::file_not_found_hook(s)) {
2663 docstring const text =
2664 bformat(_("Do you want to retrieve the document"
2665 " %1$s from version control?"), file);
2666 int const ret = Alert::prompt(_("Retrieve from version control?"),
2667 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2670 // How can we know _how_ to do the checkout?
2671 // With the current VC support it has to be,
2672 // a RCS file since CVS do not have special ,v files.
2674 return loadLyXFile(s);
2682 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2684 TeXErrors::Errors::const_iterator cit = terr.begin();
2685 TeXErrors::Errors::const_iterator end = terr.end();
2687 for (; cit != end; ++cit) {
2690 int errorRow = cit->error_in_line;
2691 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2697 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2698 } while (found && id_start == id_end && pos_start == pos_end);
2700 errorList.push_back(ErrorItem(cit->error_desc,
2701 cit->error_text, id_start, pos_start, pos_end));
2706 void Buffer::updateLabels(bool childonly) const
2708 // Use the master text class also for child documents
2709 Buffer const * const master = masterBuffer();
2710 DocumentClass const & textclass = master->params().documentClass();
2712 // keep the buffers to be children in this set. If the call from the
2713 // master comes back we can see which of them were actually seen (i.e.
2714 // via an InsetInclude). The remaining ones in the set need still be updated.
2715 static std::set<Buffer const *> bufToUpdate;
2717 // If this is a child document start with the master
2718 if (master != this) {
2719 bufToUpdate.insert(this);
2720 master->updateLabels(false);
2722 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
2723 if (bufToUpdate.find(this) == bufToUpdate.end())
2727 // start over the counters in the master
2728 textclass.counters().reset();
2731 // update will be done below for this buffer
2732 bufToUpdate.erase(this);
2734 // update all caches
2735 clearReferenceCache();
2736 inset().setBuffer(const_cast<Buffer &>(*this));
2739 Buffer & cbuf = const_cast<Buffer &>(*this);
2741 LASSERT(!text().paragraphs().empty(), /**/);
2744 ParIterator parit = cbuf.par_iterator_begin();
2745 updateLabels(parit);
2748 // TocBackend update will be done later.
2751 cbuf.tocBackend().update();
2753 cbuf.structureChanged();
2757 static depth_type getDepth(DocIterator const & it)
2759 depth_type depth = 0;
2760 for (size_t i = 0 ; i < it.depth() ; ++i)
2761 if (!it[i].inset().inMathed())
2762 depth += it[i].paragraph().getDepth() + 1;
2763 // remove 1 since the outer inset does not count
2767 static depth_type getItemDepth(ParIterator const & it)
2769 Paragraph const & par = *it;
2770 LabelType const labeltype = par.layout().labeltype;
2772 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
2775 // this will hold the lowest depth encountered up to now.
2776 depth_type min_depth = getDepth(it);
2777 ParIterator prev_it = it;
2780 --prev_it.top().pit();
2782 // start of nested inset: go to outer par
2784 if (prev_it.empty()) {
2785 // start of document: nothing to do
2790 // We search for the first paragraph with same label
2791 // that is not more deeply nested.
2792 Paragraph & prev_par = *prev_it;
2793 depth_type const prev_depth = getDepth(prev_it);
2794 if (labeltype == prev_par.layout().labeltype) {
2795 if (prev_depth < min_depth)
2796 return prev_par.itemdepth + 1;
2797 if (prev_depth == min_depth)
2798 return prev_par.itemdepth;
2800 min_depth = min(min_depth, prev_depth);
2801 // small optimization: if we are at depth 0, we won't
2802 // find anything else
2803 if (prev_depth == 0)
2809 static bool needEnumCounterReset(ParIterator const & it)
2811 Paragraph const & par = *it;
2812 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
2813 depth_type const cur_depth = par.getDepth();
2814 ParIterator prev_it = it;
2815 while (prev_it.pit()) {
2816 --prev_it.top().pit();
2817 Paragraph const & prev_par = *prev_it;
2818 if (prev_par.getDepth() <= cur_depth)
2819 return prev_par.layout().labeltype != LABEL_ENUMERATE;
2821 // start of nested inset: reset
2826 // set the label of a paragraph. This includes the counters.
2827 static void setLabel(Buffer const & buf, ParIterator & it)
2829 BufferParams const & bp = buf.masterBuffer()->params();
2830 DocumentClass const & textclass = bp.documentClass();
2831 Paragraph & par = it.paragraph();
2832 Layout const & layout = par.layout();
2833 Counters & counters = textclass.counters();
2835 if (par.params().startOfAppendix()) {
2836 // FIXME: only the counter corresponding to toplevel
2837 // sectionning should be reset
2839 counters.appendix(true);
2841 par.params().appendix(counters.appendix());
2843 // Compute the item depth of the paragraph
2844 par.itemdepth = getItemDepth(it);
2846 if (layout.margintype == MARGIN_MANUAL) {
2847 if (par.params().labelWidthString().empty())
2848 par.params().labelWidthString(par.translateIfPossible(layout.labelstring(), bp));
2850 par.params().labelWidthString(docstring());
2853 switch(layout.labeltype) {
2855 if (layout.toclevel <= bp.secnumdepth
2856 && (layout.latextype != LATEX_ENVIRONMENT
2857 || isFirstInSequence(it.pit(), it.plist()))) {
2858 counters.step(layout.counter);
2859 par.params().labelString(
2860 par.expandLabel(layout, bp));
2862 par.params().labelString(docstring());
2865 case LABEL_ITEMIZE: {
2866 // At some point of time we should do something more
2867 // clever here, like:
2868 // par.params().labelString(
2869 // bp.user_defined_bullet(par.itemdepth).getText());
2870 // for now, use a simple hardcoded label
2871 docstring itemlabel;
2872 switch (par.itemdepth) {
2874 itemlabel = char_type(0x2022);
2877 itemlabel = char_type(0x2013);
2880 itemlabel = char_type(0x2217);
2883 itemlabel = char_type(0x2219); // or 0x00b7
2886 par.params().labelString(itemlabel);
2890 case LABEL_ENUMERATE: {
2891 // FIXME: Yes I know this is a really, really! bad solution
2893 docstring enumcounter = from_ascii("enum");
2895 switch (par.itemdepth) {
2904 enumcounter += "iv";
2907 // not a valid enumdepth...
2911 // Maybe we have to reset the enumeration counter.
2912 if (needEnumCounterReset(it))
2913 counters.reset(enumcounter);
2915 counters.step(enumcounter);
2919 switch (par.itemdepth) {
2921 format = N_("\\arabic{enumi}.");
2924 format = N_("(\\alph{enumii})");
2927 format = N_("\\roman{enumiii}.");
2930 format = N_("\\Alph{enumiv}.");
2933 // not a valid enumdepth...
2937 par.params().labelString(counters.counterLabel(
2938 par.translateIfPossible(from_ascii(format), bp)));
2943 case LABEL_SENSITIVE: {
2944 string const & type = counters.current_float();
2945 docstring full_label;
2947 full_label = buf.B_("Senseless!!! ");
2949 docstring name = buf.B_(textclass.floats().getType(type).name());
2950 if (counters.hasCounter(from_utf8(type))) {
2951 counters.step(from_utf8(type));
2952 full_label = bformat(from_ascii("%1$s %2$s:"),
2954 counters.theCounter(from_utf8(type)));
2956 full_label = bformat(from_ascii("%1$s #:"), name);
2958 par.params().labelString(full_label);
2962 case LABEL_NO_LABEL:
2963 par.params().labelString(docstring());
2967 case LABEL_TOP_ENVIRONMENT:
2968 case LABEL_CENTERED_TOP_ENVIRONMENT:
2971 par.params().labelString(
2972 par.translateIfPossible(layout.labelstring(), bp));
2978 void Buffer::updateLabels(ParIterator & parit) const
2980 LASSERT(parit.pit() == 0, /**/);
2982 // set the position of the text in the buffer to be able
2983 // to resolve macros in it. This has nothing to do with
2984 // labels, but by putting it here we avoid implementing
2985 // a whole bunch of traversal routines just for this call.
2986 parit.text()->setMacrocontextPosition(parit);
2988 depth_type maxdepth = 0;
2989 pit_type const lastpit = parit.lastpit();
2990 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
2991 // reduce depth if necessary
2992 parit->params().depth(min(parit->params().depth(), maxdepth));
2993 maxdepth = parit->getMaxDepthAfter();
2995 // set the counter for this paragraph
2996 setLabel(*this, parit);
2999 InsetList::const_iterator iit = parit->insetList().begin();
3000 InsetList::const_iterator end = parit->insetList().end();
3001 for (; iit != end; ++iit) {
3002 parit.pos() = iit->pos;
3003 iit->inset->updateLabels(parit);