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 Buffer * child = const_cast<Buffer *>(it->first);
294 // The child buffer might have been closed already.
295 if (theBufferList().isLoaded(child))
296 theBufferList().releaseChild(this, child);
299 // clear references to children in macro tables
300 d->children_positions.clear();
301 d->position_to_children.clear();
303 if (!d->temppath.destroyDirectory()) {
304 Alert::warning(_("Could not remove temporary directory"),
305 bformat(_("Could not remove the temporary directory %1$s"),
306 from_utf8(d->temppath.absFilename())));
309 // Remove any previewed LaTeX snippets associated with this buffer.
310 thePreviews().removeLoader(*this);
316 void Buffer::changed() const
323 frontend::WorkAreaManager & Buffer::workAreaManager() const
325 LASSERT(d->wa_, /**/);
330 Text & Buffer::text() const
332 return d->inset->text();
336 Inset & Buffer::inset() const
342 BufferParams & Buffer::params()
348 BufferParams const & Buffer::params() const
354 ParagraphList & Buffer::paragraphs()
356 return text().paragraphs();
360 ParagraphList const & Buffer::paragraphs() const
362 return text().paragraphs();
366 LyXVC & Buffer::lyxvc()
372 LyXVC const & Buffer::lyxvc() const
378 string const Buffer::temppath() const
380 return d->temppath.absFilename();
384 TexRow & Buffer::texrow()
390 TexRow const & Buffer::texrow() const
396 TocBackend & Buffer::tocBackend() const
398 return d->toc_backend;
402 Undo & Buffer::undo()
408 string Buffer::latexName(bool const no_path) const
410 FileName latex_name = makeLatexName(d->filename);
411 return no_path ? latex_name.onlyFileName()
412 : latex_name.absFilename();
416 string Buffer::logName(LogType * type) const
418 string const filename = latexName(false);
420 if (filename.empty()) {
426 string const path = temppath();
428 FileName const fname(addName(temppath(),
429 onlyFilename(changeExtension(filename,
431 FileName const bname(
432 addName(path, onlyFilename(
433 changeExtension(filename,
434 formats.extension("literate") + ".out"))));
436 // If no Latex log or Build log is newer, show Build log
438 if (bname.exists() &&
439 (!fname.exists() || fname.lastModified() < bname.lastModified())) {
440 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
443 return bname.absFilename();
445 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
448 return fname.absFilename();
452 void Buffer::setReadonly(bool const flag)
454 if (d->read_only != flag) {
461 void Buffer::setFileName(string const & newfile)
463 d->filename = makeAbsPath(newfile);
464 setReadonly(d->filename.isReadOnly());
469 int Buffer::readHeader(Lexer & lex)
471 int unknown_tokens = 0;
473 int begin_header_line = -1;
475 // Initialize parameters that may be/go lacking in header:
476 params().branchlist().clear();
477 params().preamble.erase();
478 params().options.erase();
479 params().master.erase();
480 params().float_placement.erase();
481 params().paperwidth.erase();
482 params().paperheight.erase();
483 params().leftmargin.erase();
484 params().rightmargin.erase();
485 params().topmargin.erase();
486 params().bottommargin.erase();
487 params().headheight.erase();
488 params().headsep.erase();
489 params().footskip.erase();
490 params().columnsep.erase();
491 params().fontsCJK.erase();
492 params().listings_params.clear();
493 params().clearLayoutModules();
494 params().clearRemovedModules();
495 params().pdfoptions().clear();
497 for (int i = 0; i < 4; ++i) {
498 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
499 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
502 ErrorList & errorList = d->errorLists["Parse"];
511 if (token == "\\end_header")
515 if (token == "\\begin_header") {
516 begin_header_line = line;
520 LYXERR(Debug::PARSER, "Handling document header token: `"
523 string unknown = params().readToken(lex, token, d->filename.onlyPath());
524 if (!unknown.empty()) {
525 if (unknown[0] != '\\' && token == "\\textclass") {
526 Alert::warning(_("Unknown document class"),
527 bformat(_("Using the default document class, because the "
528 "class %1$s is unknown."), from_utf8(unknown)));
531 docstring const s = bformat(_("Unknown token: "
535 errorList.push_back(ErrorItem(_("Document header error"),
540 if (begin_header_line) {
541 docstring const s = _("\\begin_header is missing");
542 errorList.push_back(ErrorItem(_("Document header error"),
546 params().makeDocumentClass();
548 return unknown_tokens;
553 // changed to be public and have one parameter
554 // Returns true if "\end_document" is not read (Asger)
555 bool Buffer::readDocument(Lexer & lex)
557 ErrorList & errorList = d->errorLists["Parse"];
560 if (!lex.checkFor("\\begin_document")) {
561 docstring const s = _("\\begin_document is missing");
562 errorList.push_back(ErrorItem(_("Document header error"),
566 // we are reading in a brand new document
567 LASSERT(paragraphs().empty(), /**/);
571 if (params().outputChanges) {
572 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
573 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
574 LaTeXFeatures::isAvailable("xcolor");
576 if (!dvipost && !xcolorulem) {
577 Alert::warning(_("Changes not shown in LaTeX output"),
578 _("Changes will not be highlighted in LaTeX output, "
579 "because neither dvipost nor xcolor/ulem are installed.\n"
580 "Please install these packages or redefine "
581 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
582 } else if (!xcolorulem) {
583 Alert::warning(_("Changes not shown in LaTeX output"),
584 _("Changes will not be highlighted in LaTeX output "
585 "when using pdflatex, because xcolor and ulem are not installed.\n"
586 "Please install both packages or redefine "
587 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
591 if (!params().master.empty()) {
592 FileName const master_file = makeAbsPath(params().master,
593 onlyPath(absFileName()));
594 if (isLyXFilename(master_file.absFilename())) {
596 checkAndLoadLyXFile(master_file, true);
598 // set master as master buffer, but only
599 // if we are a real child
600 if (master->isChild(this))
602 // if the master is not fully loaded
603 // it is probably just loading this
604 // child. No warning needed then.
605 else if (master->isFullyLoaded())
606 LYXERR0("The master '"
608 << "' assigned to this document '"
610 << "' does not include "
611 "this document. Ignoring the master assignment.");
617 bool const res = text().read(*this, lex, errorList, d->inset);
620 updateMacroInstances();
625 // needed to insert the selection
626 void Buffer::insertStringAsLines(ParagraphList & pars,
627 pit_type & pit, pos_type & pos,
628 Font const & fn, docstring const & str, bool autobreakrows)
632 // insert the string, don't insert doublespace
633 bool space_inserted = true;
634 for (docstring::const_iterator cit = str.begin();
635 cit != str.end(); ++cit) {
636 Paragraph & par = pars[pit];
638 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
639 breakParagraph(params(), pars, pit, pos,
640 par.layout().isEnvironment());
643 space_inserted = true;
647 // do not insert consecutive spaces if !free_spacing
648 } else if ((*cit == ' ' || *cit == '\t') &&
649 space_inserted && !par.isFreeSpacing()) {
651 } else if (*cit == '\t') {
652 if (!par.isFreeSpacing()) {
653 // tabs are like spaces here
654 par.insertChar(pos, ' ', font, params().trackChanges);
656 space_inserted = true;
658 par.insertChar(pos, *cit, font, params().trackChanges);
660 space_inserted = true;
662 } else if (!isPrintable(*cit)) {
663 // Ignore unprintables
666 // just insert the character
667 par.insertChar(pos, *cit, font, params().trackChanges);
669 space_inserted = (*cit == ' ');
676 bool Buffer::readString(string const & s)
678 params().compressed = false;
680 // remove dummy empty par
681 paragraphs().clear();
685 FileName const name = FileName::tempName("Buffer_readString");
686 switch (readFile(lex, name, true)) {
690 // We need to call lyx2lyx, so write the input to a file
691 ofstream os(name.toFilesystemEncoding().c_str());
694 return readFile(name);
704 bool Buffer::readFile(FileName const & filename)
706 FileName fname(filename);
708 params().compressed = fname.isZippedFile();
710 // remove dummy empty par
711 paragraphs().clear();
714 if (readFile(lex, fname) != success)
721 bool Buffer::isFullyLoaded() const
723 return d->file_fully_loaded;
727 void Buffer::setFullyLoaded(bool value)
729 d->file_fully_loaded = value;
733 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
736 LASSERT(!filename.empty(), /**/);
738 // the first (non-comment) token _must_ be...
739 if (!lex.checkFor("\\lyxformat")) {
740 Alert::error(_("Document format failure"),
741 bformat(_("%1$s is not a readable LyX document."),
742 from_utf8(filename.absFilename())));
748 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
749 // if present remove ".," from string.
750 size_t dot = tmp_format.find_first_of(".,");
751 //lyxerr << " dot found at " << dot << endl;
752 if (dot != string::npos)
753 tmp_format.erase(dot, 1);
754 int const file_format = convert<int>(tmp_format);
755 //lyxerr << "format: " << file_format << endl;
757 // save timestamp and checksum of the original disk file, making sure
758 // to not overwrite them with those of the file created in the tempdir
759 // when it has to be converted to the current format.
761 // Save the timestamp and checksum of disk file. If filename is an
762 // emergency file, save the timestamp and checksum of the original lyx file
763 // because isExternallyModified will check for this file. (BUG4193)
764 string diskfile = filename.absFilename();
765 if (suffixIs(diskfile, ".emergency"))
766 diskfile = diskfile.substr(0, diskfile.size() - 10);
767 saveCheckSum(FileName(diskfile));
770 if (file_format != LYX_FORMAT) {
773 // lyx2lyx would fail
776 FileName const tmpfile = FileName::tempName("Buffer_readFile");
777 if (tmpfile.empty()) {
778 Alert::error(_("Conversion failed"),
779 bformat(_("%1$s is from a different"
780 " version of LyX, but a temporary"
781 " file for converting it could"
783 from_utf8(filename.absFilename())));
786 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
787 if (lyx2lyx.empty()) {
788 Alert::error(_("Conversion script not found"),
789 bformat(_("%1$s is from a different"
790 " version of LyX, but the"
791 " conversion script lyx2lyx"
792 " could not be found."),
793 from_utf8(filename.absFilename())));
796 ostringstream command;
797 command << os::python()
798 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
799 << " -t " << convert<string>(LYX_FORMAT)
800 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
801 << ' ' << quoteName(filename.toFilesystemEncoding());
802 string const command_str = command.str();
804 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
806 cmd_ret const ret = runCommand(command_str);
807 if (ret.first != 0) {
808 Alert::error(_("Conversion script failed"),
809 bformat(_("%1$s is from a different version"
810 " of LyX, but the lyx2lyx script"
811 " failed to convert it."),
812 from_utf8(filename.absFilename())));
815 bool const ret = readFile(tmpfile);
816 // Do stuff with tmpfile name and buffer name here.
817 return ret ? success : failure;
822 if (readDocument(lex)) {
823 Alert::error(_("Document format failure"),
824 bformat(_("%1$s ended unexpectedly, which means"
825 " that it is probably corrupted."),
826 from_utf8(filename.absFilename())));
829 d->file_fully_loaded = true;
834 // Should probably be moved to somewhere else: BufferView? LyXView?
835 bool Buffer::save() const
837 // We don't need autosaves in the immediate future. (Asger)
838 resetAutosaveTimers();
840 string const encodedFilename = d->filename.toFilesystemEncoding();
843 bool madeBackup = false;
845 // make a backup if the file already exists
846 if (lyxrc.make_backup && fileName().exists()) {
847 backupName = FileName(absFileName() + '~');
848 if (!lyxrc.backupdir_path.empty()) {
849 string const mangledName =
850 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
851 backupName = FileName(addName(lyxrc.backupdir_path,
854 if (fileName().copyTo(backupName)) {
857 Alert::error(_("Backup failure"),
858 bformat(_("Cannot create backup file %1$s.\n"
859 "Please check whether the directory exists and is writeable."),
860 from_utf8(backupName.absFilename())));
861 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
865 // ask if the disk file has been externally modified (use checksum method)
866 if (fileName().exists() && isExternallyModified(checksum_method)) {
867 docstring const file = makeDisplayPath(absFileName(), 20);
868 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
869 "you want to overwrite this file?"), file);
870 int const ret = Alert::prompt(_("Overwrite modified file?"),
871 text, 1, 1, _("&Overwrite"), _("&Cancel"));
876 if (writeFile(d->filename)) {
880 // Saving failed, so backup is not backup
882 backupName.moveTo(d->filename);
888 bool Buffer::writeFile(FileName const & fname) const
890 if (d->read_only && fname == d->filename)
895 docstring const str = bformat(_("Saving document %1$s..."),
896 makeDisplayPath(fname.absFilename()));
899 if (params().compressed) {
900 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
901 retval = ofs && write(ofs);
903 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
904 retval = ofs && write(ofs);
908 message(str + _(" could not write file!"));
912 removeAutosaveFile(d->filename.absFilename());
914 saveCheckSum(d->filename);
915 message(str + _(" done."));
921 bool Buffer::write(ostream & ofs) const
924 // Use the standard "C" locale for file output.
925 ofs.imbue(locale::classic());
928 // The top of the file should not be written by params().
930 // write out a comment in the top of the file
931 ofs << "#LyX " << lyx_version
932 << " created this file. For more info see http://www.lyx.org/\n"
933 << "\\lyxformat " << LYX_FORMAT << "\n"
934 << "\\begin_document\n";
936 /// For each author, set 'used' to true if there is a change
937 /// by this author in the document; otherwise set it to 'false'.
938 AuthorList::Authors::const_iterator a_it = params().authors().begin();
939 AuthorList::Authors::const_iterator a_end = params().authors().end();
940 for (; a_it != a_end; ++a_it)
941 a_it->second.setUsed(false);
943 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
944 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
945 for ( ; it != end; ++it)
946 it->checkAuthors(params().authors());
948 // now write out the buffer parameters.
949 ofs << "\\begin_header\n";
950 params().writeFile(ofs);
951 ofs << "\\end_header\n";
954 ofs << "\n\\begin_body\n";
955 text().write(*this, ofs);
956 ofs << "\n\\end_body\n";
958 // Write marker that shows file is complete
959 ofs << "\\end_document" << endl;
961 // Shouldn't really be needed....
964 // how to check if close went ok?
965 // Following is an attempt... (BE 20001011)
967 // good() returns false if any error occured, including some
969 // bad() returns true if something bad happened in the buffer,
970 // which should include file system full errors.
975 lyxerr << "File was not closed properly." << endl;
982 bool Buffer::makeLaTeXFile(FileName const & fname,
983 string const & original_path,
984 OutputParams const & runparams,
985 bool output_preamble, bool output_body) const
987 string const encoding = runparams.encoding->iconvName();
988 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
991 try { ofs.reset(encoding); }
992 catch (iconv_codecvt_facet_exception & e) {
993 lyxerr << "Caught iconv exception: " << e.what() << endl;
994 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
995 "verify that the support software for your encoding (%1$s) is "
996 "properly installed"), from_ascii(encoding)));
999 if (!openFileWrite(ofs, fname))
1002 //TexStream ts(ofs.rdbuf(), &texrow());
1003 ErrorList & errorList = d->errorLists["Export"];
1005 bool failed_export = false;
1008 writeLaTeXSource(ofs, original_path,
1009 runparams, output_preamble, output_body);
1011 catch (EncodingException & e) {
1012 odocstringstream ods;
1013 ods.put(e.failed_char);
1015 oss << "0x" << hex << e.failed_char << dec;
1016 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1017 " (code point %2$s)"),
1018 ods.str(), from_utf8(oss.str()));
1019 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1020 "representable in the chosen encoding.\n"
1021 "Changing the document encoding to utf8 could help."),
1022 e.par_id, e.pos, e.pos + 1));
1023 failed_export = true;
1025 catch (iconv_codecvt_facet_exception & e) {
1026 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1027 _(e.what()), -1, 0, 0));
1028 failed_export = true;
1030 catch (exception const & e) {
1031 errorList.push_back(ErrorItem(_("conversion failed"),
1032 _(e.what()), -1, 0, 0));
1033 failed_export = true;
1036 lyxerr << "Caught some really weird exception..." << endl;
1042 failed_export = true;
1043 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1047 return !failed_export;
1051 void Buffer::writeLaTeXSource(odocstream & os,
1052 string const & original_path,
1053 OutputParams const & runparams_in,
1054 bool const output_preamble, bool const output_body) const
1056 // The child documents, if any, shall be already loaded at this point.
1058 OutputParams runparams = runparams_in;
1060 // Classify the unicode characters appearing in math insets
1061 Encodings::initUnicodeMath(*this);
1063 // validate the buffer.
1064 LYXERR(Debug::LATEX, " Validating buffer...");
1065 LaTeXFeatures features(*this, params(), runparams);
1067 LYXERR(Debug::LATEX, " Buffer validation done.");
1069 // The starting paragraph of the coming rows is the
1070 // first paragraph of the document. (Asger)
1071 if (output_preamble && runparams.nice) {
1072 os << "%% LyX " << lyx_version << " created this file. "
1073 "For more info, see http://www.lyx.org/.\n"
1074 "%% Do not edit unless you really know what "
1076 d->texrow.newline();
1077 d->texrow.newline();
1079 LYXERR(Debug::INFO, "lyx document header finished");
1081 // Don't move this behind the parent_buffer=0 code below,
1082 // because then the macros will not get the right "redefinition"
1083 // flag as they don't see the parent macros which are output before.
1086 // fold macros if possible, still with parent buffer as the
1087 // macros will be put in the prefix anyway.
1088 updateMacroInstances();
1090 // There are a few differences between nice LaTeX and usual files:
1091 // usual is \batchmode and has a
1092 // special input@path to allow the including of figures
1093 // with either \input or \includegraphics (what figinsets do).
1094 // input@path is set when the actual parameter
1095 // original_path is set. This is done for usual tex-file, but not
1096 // for nice-latex-file. (Matthias 250696)
1097 // Note that input@path is only needed for something the user does
1098 // in the preamble, included .tex files or ERT, files included by
1099 // LyX work without it.
1100 if (output_preamble) {
1101 if (!runparams.nice) {
1102 // code for usual, NOT nice-latex-file
1103 os << "\\batchmode\n"; // changed
1104 // from \nonstopmode
1105 d->texrow.newline();
1107 if (!original_path.empty()) {
1109 // We don't know the encoding of inputpath
1110 docstring const inputpath = from_utf8(latex_path(original_path));
1111 os << "\\makeatletter\n"
1112 << "\\def\\input@path{{"
1113 << inputpath << "/}}\n"
1114 << "\\makeatother\n";
1115 d->texrow.newline();
1116 d->texrow.newline();
1117 d->texrow.newline();
1120 // get parent macros (if this buffer has a parent) which will be
1121 // written at the document begin further down.
1122 MacroSet parentMacros;
1123 listParentMacros(parentMacros, features);
1125 // Write the preamble
1126 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1128 runparams.use_japanese = features.isRequired("japanese");
1134 os << "\\begin{document}\n";
1135 d->texrow.newline();
1137 // output the parent macros
1138 MacroSet::iterator it = parentMacros.begin();
1139 MacroSet::iterator end = parentMacros.end();
1140 for (; it != end; ++it)
1141 (*it)->write(os, true);
1142 } // output_preamble
1144 d->texrow.start(paragraphs().begin()->id(), 0);
1146 LYXERR(Debug::INFO, "preamble finished, now the body.");
1148 // if we are doing a real file with body, even if this is the
1149 // child of some other buffer, let's cut the link here.
1150 // This happens for example if only a child document is printed.
1151 Buffer const * save_parent = 0;
1152 if (output_preamble) {
1153 save_parent = d->parent_buffer;
1154 d->parent_buffer = 0;
1158 latexParagraphs(*this, text(), os, d->texrow, runparams);
1160 // Restore the parenthood if needed
1161 if (output_preamble)
1162 d->parent_buffer = save_parent;
1164 // add this just in case after all the paragraphs
1166 d->texrow.newline();
1168 if (output_preamble) {
1169 os << "\\end{document}\n";
1170 d->texrow.newline();
1171 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1173 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1175 runparams_in.encoding = runparams.encoding;
1177 // Just to be sure. (Asger)
1178 d->texrow.newline();
1180 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1181 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1185 bool Buffer::isLatex() const
1187 return params().documentClass().outputType() == LATEX;
1191 bool Buffer::isLiterate() const
1193 return params().documentClass().outputType() == LITERATE;
1197 bool Buffer::isDocBook() const
1199 return params().documentClass().outputType() == DOCBOOK;
1203 void Buffer::makeDocBookFile(FileName const & fname,
1204 OutputParams const & runparams,
1205 bool const body_only) const
1207 LYXERR(Debug::LATEX, "makeDocBookFile...");
1210 if (!openFileWrite(ofs, fname))
1213 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1217 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1221 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1222 OutputParams const & runparams,
1223 bool const only_body) const
1225 LaTeXFeatures features(*this, params(), runparams);
1230 DocumentClass const & tclass = params().documentClass();
1231 string const top_element = tclass.latexname();
1234 if (runparams.flavor == OutputParams::XML)
1235 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1238 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1241 if (! tclass.class_header().empty())
1242 os << from_ascii(tclass.class_header());
1243 else if (runparams.flavor == OutputParams::XML)
1244 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1245 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1247 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1249 docstring preamble = from_utf8(params().preamble);
1250 if (runparams.flavor != OutputParams::XML ) {
1251 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1252 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1253 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1254 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1257 string const name = runparams.nice
1258 ? changeExtension(absFileName(), ".sgml") : fname;
1259 preamble += features.getIncludedFiles(name);
1260 preamble += features.getLyXSGMLEntities();
1262 if (!preamble.empty()) {
1263 os << "\n [ " << preamble << " ]";
1268 string top = top_element;
1270 if (runparams.flavor == OutputParams::XML)
1271 top += params().language->code();
1273 top += params().language->code().substr(0, 2);
1276 if (!params().options.empty()) {
1278 top += params().options;
1281 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1282 << " file was created by LyX " << lyx_version
1283 << "\n See http://www.lyx.org/ for more information -->\n";
1285 params().documentClass().counters().reset();
1289 sgml::openTag(os, top);
1291 docbookParagraphs(paragraphs(), *this, os, runparams);
1292 sgml::closeTag(os, top_element);
1296 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1297 // Other flags: -wall -v0 -x
1298 int Buffer::runChktex()
1302 // get LaTeX-Filename
1303 FileName const path(temppath());
1304 string const name = addName(path.absFilename(), latexName());
1305 string const org_path = filePath();
1307 PathChanger p(path); // path to LaTeX file
1308 message(_("Running chktex..."));
1310 // Generate the LaTeX file if neccessary
1311 OutputParams runparams(¶ms().encoding());
1312 runparams.flavor = OutputParams::LATEX;
1313 runparams.nice = false;
1314 makeLaTeXFile(FileName(name), org_path, runparams);
1317 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1318 int const res = chktex.run(terr); // run chktex
1321 Alert::error(_("chktex failure"),
1322 _("Could not run chktex successfully."));
1323 } else if (res > 0) {
1324 ErrorList & errlist = d->errorLists["ChkTeX"];
1326 bufferErrors(terr, errlist);
1337 void Buffer::validate(LaTeXFeatures & features) const
1339 params().validate(features);
1343 for_each(paragraphs().begin(), paragraphs().end(),
1344 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1346 if (lyxerr.debugging(Debug::LATEX)) {
1347 features.showStruct();
1352 void Buffer::getLabelList(vector<docstring> & list) const
1354 // If this is a child document, use the parent's list instead.
1355 if (d->parent_buffer) {
1356 d->parent_buffer->getLabelList(list);
1361 Toc & toc = d->toc_backend.toc("label");
1362 TocIterator toc_it = toc.begin();
1363 TocIterator end = toc.end();
1364 for (; toc_it != end; ++toc_it) {
1365 if (toc_it->depth() == 0)
1366 list.push_back(toc_it->str());
1371 void Buffer::updateBibfilesCache() const
1373 // If this is a child document, use the parent's cache instead.
1374 if (d->parent_buffer) {
1375 d->parent_buffer->updateBibfilesCache();
1379 d->bibfilesCache_.clear();
1380 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1381 if (it->lyxCode() == BIBTEX_CODE) {
1382 InsetBibtex const & inset =
1383 static_cast<InsetBibtex const &>(*it);
1384 support::FileNameList const bibfiles = inset.getBibFiles();
1385 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1388 } else if (it->lyxCode() == INCLUDE_CODE) {
1389 InsetInclude & inset =
1390 static_cast<InsetInclude &>(*it);
1391 inset.updateBibfilesCache();
1392 support::FileNameList const & bibfiles =
1393 inset.getBibfilesCache(*this);
1394 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1399 // the bibinfo cache is now invalid
1400 d->bibinfoCacheValid_ = false;
1404 void Buffer::invalidateBibinfoCache()
1406 d->bibinfoCacheValid_ = false;
1410 support::FileNameList const & Buffer::getBibfilesCache() const
1412 // If this is a child document, use the parent's cache instead.
1413 if (d->parent_buffer)
1414 return d->parent_buffer->getBibfilesCache();
1416 // We update the cache when first used instead of at loading time.
1417 if (d->bibfilesCache_.empty())
1418 const_cast<Buffer *>(this)->updateBibfilesCache();
1420 return d->bibfilesCache_;
1424 BiblioInfo const & Buffer::masterBibInfo() const
1426 // if this is a child document and the parent is already loaded
1427 // use the parent's list instead [ale990412]
1428 Buffer const * const tmp = masterBuffer();
1431 return tmp->masterBibInfo();
1432 return localBibInfo();
1436 BiblioInfo const & Buffer::localBibInfo() const
1438 if (d->bibinfoCacheValid_) {
1439 support::FileNameList const & bibfilesCache = getBibfilesCache();
1440 // compare the cached timestamps with the actual ones.
1441 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1442 support::FileNameList::const_iterator en = bibfilesCache.end();
1443 for (; ei != en; ++ ei) {
1444 time_t lastw = ei->lastModified();
1445 if (lastw != d->bibfileStatus_[*ei]) {
1446 d->bibinfoCacheValid_ = false;
1447 d->bibfileStatus_[*ei] = lastw;
1453 if (!d->bibinfoCacheValid_) {
1454 d->bibinfo_.clear();
1455 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1456 it->fillWithBibKeys(d->bibinfo_, it);
1457 d->bibinfoCacheValid_ = true;
1463 bool Buffer::isDepClean(string const & name) const
1465 DepClean::const_iterator const it = d->dep_clean.find(name);
1466 if (it == d->dep_clean.end())
1472 void Buffer::markDepClean(string const & name)
1474 d->dep_clean[name] = true;
1478 bool Buffer::dispatch(string const & command, bool * result)
1480 return dispatch(lyxaction.lookupFunc(command), result);
1484 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1486 bool dispatched = true;
1488 switch (func.action) {
1489 case LFUN_BUFFER_EXPORT: {
1490 bool const tmp = doExport(to_utf8(func.argument()), false);
1496 case LFUN_BRANCH_ACTIVATE:
1497 case LFUN_BRANCH_DEACTIVATE: {
1498 BranchList & branchList = params().branchlist();
1499 docstring const branchName = func.argument();
1500 Branch * branch = branchList.find(branchName);
1502 LYXERR0("Branch " << branchName << " does not exist.");
1504 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1516 void Buffer::changeLanguage(Language const * from, Language const * to)
1518 LASSERT(from, /**/);
1521 for_each(par_iterator_begin(),
1523 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1527 bool Buffer::isMultiLingual() const
1529 ParConstIterator end = par_iterator_end();
1530 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1531 if (it->isMultiLingual(params()))
1538 DocIterator Buffer::getParFromID(int const id) const
1540 Buffer * buf = const_cast<Buffer *>(this);
1542 // John says this is called with id == -1 from undo
1543 lyxerr << "getParFromID(), id: " << id << endl;
1544 return doc_iterator_end(buf);
1547 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
1548 if (it.paragraph().id() == id)
1551 return doc_iterator_end(buf);
1555 bool Buffer::hasParWithID(int const id) const
1557 return !getParFromID(id).atEnd();
1561 ParIterator Buffer::par_iterator_begin()
1563 return ParIterator(doc_iterator_begin(this));
1567 ParIterator Buffer::par_iterator_end()
1569 return ParIterator(doc_iterator_end(this));
1573 ParConstIterator Buffer::par_iterator_begin() const
1575 return ParConstIterator(doc_iterator_begin(this));
1579 ParConstIterator Buffer::par_iterator_end() const
1581 return ParConstIterator(doc_iterator_end(this));
1585 Language const * Buffer::language() const
1587 return params().language;
1591 docstring const Buffer::B_(string const & l10n) const
1593 return params().B_(l10n);
1597 bool Buffer::isClean() const
1599 return d->lyx_clean;
1603 bool Buffer::isBakClean() const
1605 return d->bak_clean;
1609 bool Buffer::isExternallyModified(CheckMethod method) const
1611 LASSERT(d->filename.exists(), /**/);
1612 // if method == timestamp, check timestamp before checksum
1613 return (method == checksum_method
1614 || d->timestamp_ != d->filename.lastModified())
1615 && d->checksum_ != d->filename.checksum();
1619 void Buffer::saveCheckSum(FileName const & file) const
1621 if (file.exists()) {
1622 d->timestamp_ = file.lastModified();
1623 d->checksum_ = file.checksum();
1625 // in the case of save to a new file.
1632 void Buffer::markClean() const
1634 if (!d->lyx_clean) {
1635 d->lyx_clean = true;
1638 // if the .lyx file has been saved, we don't need an
1640 d->bak_clean = true;
1644 void Buffer::markBakClean() const
1646 d->bak_clean = true;
1650 void Buffer::setUnnamed(bool flag)
1656 bool Buffer::isUnnamed() const
1662 // FIXME: this function should be moved to buffer_pimpl.C
1663 void Buffer::markDirty()
1666 d->lyx_clean = false;
1669 d->bak_clean = false;
1671 DepClean::iterator it = d->dep_clean.begin();
1672 DepClean::const_iterator const end = d->dep_clean.end();
1674 for (; it != end; ++it)
1679 FileName Buffer::fileName() const
1685 string Buffer::absFileName() const
1687 return d->filename.absFilename();
1691 string Buffer::filePath() const
1693 return d->filename.onlyPath().absFilename() + "/";
1697 bool Buffer::isReadonly() const
1699 return d->read_only;
1703 void Buffer::setParent(Buffer const * buffer)
1705 // Avoids recursive include.
1706 d->parent_buffer = buffer == this ? 0 : buffer;
1711 Buffer const * Buffer::parent() const
1713 return d->parent_buffer;
1717 void Buffer::collectRelatives(BufferSet & bufs) const
1721 parent()->collectRelatives(bufs);
1723 // loop over children
1724 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
1725 Impl::BufferPositionMap::iterator end = d->children_positions.end();
1726 for (; it != end; ++it)
1727 bufs.insert(const_cast<Buffer *>(it->first));
1731 std::vector<Buffer const *> Buffer::allRelatives() const
1734 collectRelatives(bufs);
1735 BufferSet::iterator it = bufs.begin();
1736 std::vector<Buffer const *> ret;
1737 for (; it != bufs.end(); ++it)
1743 Buffer const * Buffer::masterBuffer() const
1745 if (!d->parent_buffer)
1748 return d->parent_buffer->masterBuffer();
1752 bool Buffer::isChild(Buffer * child) const
1754 return d->children_positions.find(child) != d->children_positions.end();
1758 DocIterator Buffer::firstChildPosition(Buffer const * child)
1760 Impl::BufferPositionMap::iterator it;
1761 it = d->children_positions.find(child);
1762 if (it == d->children_positions.end())
1763 return DocIterator(this);
1768 template<typename M>
1769 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
1774 typename M::iterator it = m.lower_bound(x);
1775 if (it == m.begin())
1783 MacroData const * Buffer::getBufferMacro(docstring const & name,
1784 DocIterator const & pos) const
1786 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
1788 // if paragraphs have no macro context set, pos will be empty
1792 // we haven't found anything yet
1793 DocIterator bestPos = par_iterator_begin();
1794 MacroData const * bestData = 0;
1796 // find macro definitions for name
1797 Impl::NamePositionScopeMacroMap::iterator nameIt
1798 = d->macros.find(name);
1799 if (nameIt != d->macros.end()) {
1800 // find last definition in front of pos or at pos itself
1801 Impl::PositionScopeMacroMap::const_iterator it
1802 = greatest_below(nameIt->second, pos);
1803 if (it != nameIt->second.end()) {
1805 // scope ends behind pos?
1806 if (pos < it->second.first) {
1807 // Looks good, remember this. If there
1808 // is no external macro behind this,
1809 // we found the right one already.
1810 bestPos = it->first;
1811 bestData = &it->second.second;
1815 // try previous macro if there is one
1816 if (it == nameIt->second.begin())
1823 // find macros in included files
1824 Impl::PositionScopeBufferMap::const_iterator it
1825 = greatest_below(d->position_to_children, pos);
1826 if (it == d->position_to_children.end())
1827 // no children before
1831 // do we know something better (i.e. later) already?
1832 if (it->first < bestPos )
1835 // scope ends behind pos?
1836 if (pos < it->second.first) {
1837 // look for macro in external file
1838 d->macro_lock = true;
1839 MacroData const * data
1840 = it->second.second->getMacro(name, false);
1841 d->macro_lock = false;
1843 bestPos = it->first;
1849 // try previous file if there is one
1850 if (it == d->position_to_children.begin())
1855 // return the best macro we have found
1860 MacroData const * Buffer::getMacro(docstring const & name,
1861 DocIterator const & pos, bool global) const
1866 // query buffer macros
1867 MacroData const * data = getBufferMacro(name, pos);
1871 // If there is a master buffer, query that
1872 if (d->parent_buffer) {
1873 d->macro_lock = true;
1874 MacroData const * macro = d->parent_buffer->getMacro(
1875 name, *this, false);
1876 d->macro_lock = false;
1882 data = MacroTable::globalMacros().get(name);
1891 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
1893 // set scope end behind the last paragraph
1894 DocIterator scope = par_iterator_begin();
1895 scope.pit() = scope.lastpit() + 1;
1897 return getMacro(name, scope, global);
1901 MacroData const * Buffer::getMacro(docstring const & name,
1902 Buffer const & child, bool global) const
1904 // look where the child buffer is included first
1905 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
1906 if (it == d->children_positions.end())
1909 // check for macros at the inclusion position
1910 return getMacro(name, it->second, global);
1914 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
1916 pit_type lastpit = it.lastpit();
1918 // look for macros in each paragraph
1919 while (it.pit() <= lastpit) {
1920 Paragraph & par = it.paragraph();
1922 // iterate over the insets of the current paragraph
1923 InsetList const & insets = par.insetList();
1924 InsetList::const_iterator iit = insets.begin();
1925 InsetList::const_iterator end = insets.end();
1926 for (; iit != end; ++iit) {
1927 it.pos() = iit->pos;
1929 // is it a nested text inset?
1930 if (iit->inset->asInsetText()) {
1931 // Inset needs its own scope?
1932 InsetText const * itext
1933 = iit->inset->asInsetText();
1934 bool newScope = itext->isMacroScope();
1936 // scope which ends just behind the inset
1937 DocIterator insetScope = it;
1940 // collect macros in inset
1941 it.push_back(CursorSlice(*iit->inset));
1942 updateMacros(it, newScope ? insetScope : scope);
1947 // is it an external file?
1948 if (iit->inset->lyxCode() == INCLUDE_CODE) {
1949 // get buffer of external file
1950 InsetInclude const & inset
1951 = static_cast<InsetInclude const &>(*iit->inset);
1952 d->macro_lock = true;
1953 Buffer * child = inset.loadIfNeeded(*this);
1954 d->macro_lock = false;
1958 // register its position, but only when it is
1959 // included first in the buffer
1960 if (d->children_positions.find(child)
1961 == d->children_positions.end())
1962 d->children_positions[child] = it;
1964 // register child with its scope
1965 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
1969 if (iit->inset->lyxCode() != MATHMACRO_CODE)
1973 MathMacroTemplate & macroTemplate
1974 = static_cast<MathMacroTemplate &>(*iit->inset);
1975 MacroContext mc(*this, it);
1976 macroTemplate.updateToContext(mc);
1979 bool valid = macroTemplate.validMacro();
1980 // FIXME: Should be fixNameAndCheckIfValid() in fact,
1981 // then the BufferView's cursor will be invalid in
1982 // some cases which leads to crashes.
1987 d->macros[macroTemplate.name()][it] =
1988 Impl::ScopeMacro(scope, MacroData(*this, it));
1998 void Buffer::updateMacros() const
2003 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2005 // start with empty table
2007 d->children_positions.clear();
2008 d->position_to_children.clear();
2010 // Iterate over buffer, starting with first paragraph
2011 // The scope must be bigger than any lookup DocIterator
2012 // later. For the global lookup, lastpit+1 is used, hence
2013 // we use lastpit+2 here.
2014 DocIterator it = par_iterator_begin();
2015 DocIterator outerScope = it;
2016 outerScope.pit() = outerScope.lastpit() + 2;
2017 updateMacros(it, outerScope);
2021 void Buffer::updateMacroInstances() const
2023 LYXERR(Debug::MACROS, "updateMacroInstances for "
2024 << d->filename.onlyFileName());
2025 DocIterator it = doc_iterator_begin(this);
2026 DocIterator end = doc_iterator_end(this);
2027 for (; it != end; it.forwardPos()) {
2028 // look for MathData cells in InsetMathNest insets
2029 Inset * inset = it.nextInset();
2033 InsetMath * minset = inset->asInsetMath();
2037 // update macro in all cells of the InsetMathNest
2038 DocIterator::idx_type n = minset->nargs();
2039 MacroContext mc = MacroContext(*this, it);
2040 for (DocIterator::idx_type i = 0; i < n; ++i) {
2041 MathData & data = minset->cell(i);
2042 data.updateMacros(0, mc);
2048 void Buffer::listMacroNames(MacroNameSet & macros) const
2053 d->macro_lock = true;
2055 // loop over macro names
2056 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2057 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2058 for (; nameIt != nameEnd; ++nameIt)
2059 macros.insert(nameIt->first);
2061 // loop over children
2062 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2063 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2064 for (; it != end; ++it)
2065 it->first->listMacroNames(macros);
2068 if (d->parent_buffer)
2069 d->parent_buffer->listMacroNames(macros);
2071 d->macro_lock = false;
2075 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2077 if (!d->parent_buffer)
2081 d->parent_buffer->listMacroNames(names);
2084 MacroNameSet::iterator it = names.begin();
2085 MacroNameSet::iterator end = names.end();
2086 for (; it != end; ++it) {
2088 MacroData const * data =
2089 d->parent_buffer->getMacro(*it, *this, false);
2091 macros.insert(data);
2093 // we cannot access the original MathMacroTemplate anymore
2094 // here to calls validate method. So we do its work here manually.
2095 // FIXME: somehow make the template accessible here.
2096 if (data->optionals() > 0)
2097 features.require("xargs");
2103 Buffer::References & Buffer::references(docstring const & label)
2105 if (d->parent_buffer)
2106 return const_cast<Buffer *>(masterBuffer())->references(label);
2108 RefCache::iterator it = d->ref_cache_.find(label);
2109 if (it != d->ref_cache_.end())
2110 return it->second.second;
2112 static InsetLabel const * dummy_il = 0;
2113 static References const dummy_refs;
2114 it = d->ref_cache_.insert(
2115 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2116 return it->second.second;
2120 Buffer::References const & Buffer::references(docstring const & label) const
2122 return const_cast<Buffer *>(this)->references(label);
2126 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2128 masterBuffer()->d->ref_cache_[label].first = il;
2132 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2134 return masterBuffer()->d->ref_cache_[label].first;
2138 void Buffer::clearReferenceCache() const
2140 if (!d->parent_buffer)
2141 d->ref_cache_.clear();
2145 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2148 //FIXME: This does not work for child documents yet.
2149 LASSERT(code == CITE_CODE, /**/);
2150 // Check if the label 'from' appears more than once
2151 vector<docstring> labels;
2153 BiblioInfo const & keys = masterBibInfo();
2154 BiblioInfo::const_iterator bit = keys.begin();
2155 BiblioInfo::const_iterator bend = keys.end();
2157 for (; bit != bend; ++bit)
2159 labels.push_back(bit->first);
2162 if (count(labels.begin(), labels.end(), from) > 1)
2165 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2166 if (it->lyxCode() == code) {
2167 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2168 docstring const oldValue = inset.getParam(paramName);
2169 if (oldValue == from)
2170 inset.setParam(paramName, to);
2176 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2177 pit_type par_end, bool full_source) const
2179 OutputParams runparams(¶ms().encoding());
2180 runparams.nice = true;
2181 runparams.flavor = OutputParams::LATEX;
2182 runparams.linelen = lyxrc.plaintext_linelen;
2183 // No side effect of file copying and image conversion
2184 runparams.dryrun = true;
2188 os << "% " << _("Preview source code") << "\n\n";
2189 d->texrow.newline();
2190 d->texrow.newline();
2192 writeDocBookSource(os, absFileName(), runparams, false);
2194 // latex or literate
2195 writeLaTeXSource(os, string(), runparams, true, true);
2197 runparams.par_begin = par_begin;
2198 runparams.par_end = par_end;
2199 if (par_begin + 1 == par_end) {
2201 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2205 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2206 convert<docstring>(par_begin),
2207 convert<docstring>(par_end - 1))
2210 d->texrow.newline();
2211 d->texrow.newline();
2212 // output paragraphs
2214 docbookParagraphs(paragraphs(), *this, os, runparams);
2216 // latex or literate
2217 latexParagraphs(*this, text(), os, d->texrow, runparams);
2222 ErrorList & Buffer::errorList(string const & type) const
2224 static ErrorList emptyErrorList;
2225 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2226 if (I == d->errorLists.end())
2227 return emptyErrorList;
2233 void Buffer::updateTocItem(std::string const & type,
2234 DocIterator const & dit) const
2237 gui_->updateTocItem(type, dit);
2241 void Buffer::structureChanged() const
2244 gui_->structureChanged();
2248 void Buffer::errors(string const & err) const
2255 void Buffer::message(docstring const & msg) const
2262 void Buffer::setBusy(bool on) const
2269 void Buffer::setReadOnly(bool on) const
2272 d->wa_->setReadOnly(on);
2276 void Buffer::updateTitles() const
2279 d->wa_->updateTitles();
2283 void Buffer::resetAutosaveTimers() const
2286 gui_->resetAutosaveTimers();
2290 bool Buffer::hasGuiDelegate() const
2296 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2305 class AutoSaveBuffer : public ForkedProcess {
2308 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2309 : buffer_(buffer), fname_(fname) {}
2311 virtual boost::shared_ptr<ForkedProcess> clone() const
2313 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2318 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2319 from_utf8(fname_.absFilename())));
2320 return run(DontWait);
2324 virtual int generateChild();
2326 Buffer const & buffer_;
2331 int AutoSaveBuffer::generateChild()
2333 // tmp_ret will be located (usually) in /tmp
2334 // will that be a problem?
2335 // Note that this calls ForkedCalls::fork(), so it's
2336 // ok cross-platform.
2337 pid_t const pid = fork();
2338 // If you want to debug the autosave
2339 // you should set pid to -1, and comment out the fork.
2340 if (pid != 0 && pid != -1)
2343 // pid = -1 signifies that lyx was unable
2344 // to fork. But we will do the save
2346 bool failed = false;
2347 FileName const tmp_ret = FileName::tempName("lyxauto");
2348 if (!tmp_ret.empty()) {
2349 buffer_.writeFile(tmp_ret);
2350 // assume successful write of tmp_ret
2351 if (!tmp_ret.moveTo(fname_))
2357 // failed to write/rename tmp_ret so try writing direct
2358 if (!buffer_.writeFile(fname_)) {
2359 // It is dangerous to do this in the child,
2360 // but safe in the parent, so...
2361 if (pid == -1) // emit message signal.
2362 buffer_.message(_("Autosave failed!"));
2366 if (pid == 0) // we are the child so...
2375 // Perfect target for a thread...
2376 void Buffer::autoSave() const
2378 if (isBakClean() || isReadonly()) {
2379 // We don't save now, but we'll try again later
2380 resetAutosaveTimers();
2384 // emit message signal.
2385 message(_("Autosaving current document..."));
2387 // create autosave filename
2388 string fname = filePath();
2390 fname += d->filename.onlyFileName();
2393 AutoSaveBuffer autosave(*this, FileName(fname));
2397 resetAutosaveTimers();
2401 string Buffer::bufferFormat() const
2407 if (params().encoding().package() == Encoding::japanese)
2413 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2414 string & result_file) const
2416 string backend_format;
2417 OutputParams runparams(¶ms().encoding());
2418 runparams.flavor = OutputParams::LATEX;
2419 runparams.linelen = lyxrc.plaintext_linelen;
2420 vector<string> backs = backends();
2421 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2422 // Get shortest path to format
2423 Graph::EdgePath path;
2424 for (vector<string>::const_iterator it = backs.begin();
2425 it != backs.end(); ++it) {
2426 Graph::EdgePath p = theConverters().getPath(*it, format);
2427 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2428 backend_format = *it;
2433 runparams.flavor = theConverters().getFlavor(path);
2435 Alert::error(_("Couldn't export file"),
2436 bformat(_("No information for exporting the format %1$s."),
2437 formats.prettyName(format)));
2441 backend_format = format;
2442 // FIXME: Don't hardcode format names here, but use a flag
2443 if (backend_format == "pdflatex")
2444 runparams.flavor = OutputParams::PDFLATEX;
2447 string filename = latexName(false);
2448 filename = addName(temppath(), filename);
2449 filename = changeExtension(filename,
2450 formats.extension(backend_format));
2453 updateMacroInstances();
2455 // Plain text backend
2456 if (backend_format == "text")
2457 writePlaintextFile(*this, FileName(filename), runparams);
2459 else if (backend_format == "lyx")
2460 writeFile(FileName(filename));
2462 else if (isDocBook()) {
2463 runparams.nice = !put_in_tempdir;
2464 makeDocBookFile(FileName(filename), runparams);
2467 else if (backend_format == format) {
2468 runparams.nice = true;
2469 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2471 } else if (!lyxrc.tex_allows_spaces
2472 && contains(filePath(), ' ')) {
2473 Alert::error(_("File name error"),
2474 _("The directory path to the document cannot contain spaces."));
2477 runparams.nice = false;
2478 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2482 string const error_type = (format == "program")
2483 ? "Build" : bufferFormat();
2484 ErrorList & error_list = d->errorLists[error_type];
2485 string const ext = formats.extension(format);
2486 FileName const tmp_result_file(changeExtension(filename, ext));
2487 bool const success = theConverters().convert(this, FileName(filename),
2488 tmp_result_file, FileName(absFileName()), backend_format, format,
2490 // Emit the signal to show the error list.
2491 if (format != backend_format)
2496 if (put_in_tempdir) {
2497 result_file = tmp_result_file.absFilename();
2501 result_file = changeExtension(absFileName(), ext);
2502 // We need to copy referenced files (e. g. included graphics
2503 // if format == "dvi") to the result dir.
2504 vector<ExportedFile> const files =
2505 runparams.exportdata->externalFiles(format);
2506 string const dest = onlyPath(result_file);
2507 CopyStatus status = SUCCESS;
2508 for (vector<ExportedFile>::const_iterator it = files.begin();
2509 it != files.end() && status != CANCEL; ++it) {
2510 string const fmt = formats.getFormatFromFile(it->sourceName);
2511 status = copyFile(fmt, it->sourceName,
2512 makeAbsPath(it->exportName, dest),
2513 it->exportName, status == FORCE);
2515 if (status == CANCEL) {
2516 message(_("Document export cancelled."));
2517 } else if (tmp_result_file.exists()) {
2518 // Finally copy the main file
2519 status = copyFile(format, tmp_result_file,
2520 FileName(result_file), result_file,
2522 message(bformat(_("Document exported as %1$s "
2524 formats.prettyName(format),
2525 makeDisplayPath(result_file)));
2527 // This must be a dummy converter like fax (bug 1888)
2528 message(bformat(_("Document exported as %1$s"),
2529 formats.prettyName(format)));
2536 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2539 return doExport(format, put_in_tempdir, result_file);
2543 bool Buffer::preview(string const & format) const
2546 if (!doExport(format, true, result_file))
2548 return formats.view(*this, FileName(result_file), format);
2552 bool Buffer::isExportable(string const & format) const
2554 vector<string> backs = backends();
2555 for (vector<string>::const_iterator it = backs.begin();
2556 it != backs.end(); ++it)
2557 if (theConverters().isReachable(*it, format))
2563 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2565 vector<string> backs = backends();
2566 vector<Format const *> result =
2567 theConverters().getReachable(backs[0], only_viewable, true);
2568 for (vector<string>::const_iterator it = backs.begin() + 1;
2569 it != backs.end(); ++it) {
2570 vector<Format const *> r =
2571 theConverters().getReachable(*it, only_viewable, false);
2572 result.insert(result.end(), r.begin(), r.end());
2578 vector<string> Buffer::backends() const
2581 if (params().baseClass()->isTeXClassAvailable()) {
2582 v.push_back(bufferFormat());
2583 // FIXME: Don't hardcode format names here, but use a flag
2584 if (v.back() == "latex")
2585 v.push_back("pdflatex");
2587 v.push_back("text");
2593 bool Buffer::readFileHelper(FileName const & s)
2595 // File information about normal file
2597 docstring const file = makeDisplayPath(s.absFilename(), 50);
2598 docstring text = bformat(_("The specified document\n%1$s"
2599 "\ncould not be read."), file);
2600 Alert::error(_("Could not read document"), text);
2604 // Check if emergency save file exists and is newer.
2605 FileName const e(s.absFilename() + ".emergency");
2607 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2608 docstring const file = makeDisplayPath(s.absFilename(), 20);
2609 docstring const text =
2610 bformat(_("An emergency save of the document "
2612 "Recover emergency save?"), file);
2613 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2614 _("&Recover"), _("&Load Original"),
2618 // the file is not saved if we load the emergency file.
2628 // Now check if autosave file is newer.
2629 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2631 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2632 docstring const file = makeDisplayPath(s.absFilename(), 20);
2633 docstring const text =
2634 bformat(_("The backup of the document "
2635 "%1$s is newer.\n\nLoad the "
2636 "backup instead?"), file);
2637 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2638 _("&Load backup"), _("Load &original"),
2642 // the file is not saved if we load the autosave file.
2646 // Here we delete the autosave
2657 bool Buffer::loadLyXFile(FileName const & s)
2659 if (s.isReadableFile()) {
2660 if (readFileHelper(s)) {
2661 lyxvc().file_found_hook(s);
2662 if (!s.isWritable())
2667 docstring const file = makeDisplayPath(s.absFilename(), 20);
2668 // Here we probably should run
2669 if (LyXVC::file_not_found_hook(s)) {
2670 docstring const text =
2671 bformat(_("Do you want to retrieve the document"
2672 " %1$s from version control?"), file);
2673 int const ret = Alert::prompt(_("Retrieve from version control?"),
2674 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2677 // How can we know _how_ to do the checkout?
2678 // With the current VC support it has to be,
2679 // a RCS file since CVS do not have special ,v files.
2681 return loadLyXFile(s);
2689 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2691 TeXErrors::Errors::const_iterator cit = terr.begin();
2692 TeXErrors::Errors::const_iterator end = terr.end();
2694 for (; cit != end; ++cit) {
2697 int errorRow = cit->error_in_line;
2698 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2704 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2705 } while (found && id_start == id_end && pos_start == pos_end);
2707 errorList.push_back(ErrorItem(cit->error_desc,
2708 cit->error_text, id_start, pos_start, pos_end));
2713 void Buffer::updateLabels(bool childonly) const
2715 // Use the master text class also for child documents
2716 Buffer const * const master = masterBuffer();
2717 DocumentClass const & textclass = master->params().documentClass();
2719 // keep the buffers to be children in this set. If the call from the
2720 // master comes back we can see which of them were actually seen (i.e.
2721 // via an InsetInclude). The remaining ones in the set need still be updated.
2722 static std::set<Buffer const *> bufToUpdate;
2724 // If this is a child document start with the master
2725 if (master != this) {
2726 bufToUpdate.insert(this);
2727 master->updateLabels(false);
2728 // Do this here in case the master has no gui associated with it. Then,
2729 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
2733 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
2734 if (bufToUpdate.find(this) == bufToUpdate.end())
2738 // start over the counters in the master
2739 textclass.counters().reset();
2742 // update will be done below for this buffer
2743 bufToUpdate.erase(this);
2745 // update all caches
2746 clearReferenceCache();
2747 inset().setBuffer(const_cast<Buffer &>(*this));
2750 Buffer & cbuf = const_cast<Buffer &>(*this);
2752 LASSERT(!text().paragraphs().empty(), /**/);
2755 ParIterator parit = cbuf.par_iterator_begin();
2756 updateLabels(parit);
2759 // TocBackend update will be done later.
2762 cbuf.tocBackend().update();
2764 cbuf.structureChanged();
2768 static depth_type getDepth(DocIterator const & it)
2770 depth_type depth = 0;
2771 for (size_t i = 0 ; i < it.depth() ; ++i)
2772 if (!it[i].inset().inMathed())
2773 depth += it[i].paragraph().getDepth() + 1;
2774 // remove 1 since the outer inset does not count
2778 static depth_type getItemDepth(ParIterator const & it)
2780 Paragraph const & par = *it;
2781 LabelType const labeltype = par.layout().labeltype;
2783 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
2786 // this will hold the lowest depth encountered up to now.
2787 depth_type min_depth = getDepth(it);
2788 ParIterator prev_it = it;
2791 --prev_it.top().pit();
2793 // start of nested inset: go to outer par
2795 if (prev_it.empty()) {
2796 // start of document: nothing to do
2801 // We search for the first paragraph with same label
2802 // that is not more deeply nested.
2803 Paragraph & prev_par = *prev_it;
2804 depth_type const prev_depth = getDepth(prev_it);
2805 if (labeltype == prev_par.layout().labeltype) {
2806 if (prev_depth < min_depth)
2807 return prev_par.itemdepth + 1;
2808 if (prev_depth == min_depth)
2809 return prev_par.itemdepth;
2811 min_depth = min(min_depth, prev_depth);
2812 // small optimization: if we are at depth 0, we won't
2813 // find anything else
2814 if (prev_depth == 0)
2820 static bool needEnumCounterReset(ParIterator const & it)
2822 Paragraph const & par = *it;
2823 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
2824 depth_type const cur_depth = par.getDepth();
2825 ParIterator prev_it = it;
2826 while (prev_it.pit()) {
2827 --prev_it.top().pit();
2828 Paragraph const & prev_par = *prev_it;
2829 if (prev_par.getDepth() <= cur_depth)
2830 return prev_par.layout().labeltype != LABEL_ENUMERATE;
2832 // start of nested inset: reset
2837 // set the label of a paragraph. This includes the counters.
2838 static void setLabel(Buffer const & buf, ParIterator & it)
2840 BufferParams const & bp = buf.masterBuffer()->params();
2841 DocumentClass const & textclass = bp.documentClass();
2842 Paragraph & par = it.paragraph();
2843 Layout const & layout = par.layout();
2844 Counters & counters = textclass.counters();
2846 if (par.params().startOfAppendix()) {
2847 // FIXME: only the counter corresponding to toplevel
2848 // sectionning should be reset
2850 counters.appendix(true);
2852 par.params().appendix(counters.appendix());
2854 // Compute the item depth of the paragraph
2855 par.itemdepth = getItemDepth(it);
2857 if (layout.margintype == MARGIN_MANUAL) {
2858 if (par.params().labelWidthString().empty())
2859 par.params().labelWidthString(par.translateIfPossible(layout.labelstring(), bp));
2861 par.params().labelWidthString(docstring());
2864 switch(layout.labeltype) {
2866 if (layout.toclevel <= bp.secnumdepth
2867 && (layout.latextype != LATEX_ENVIRONMENT
2868 || isFirstInSequence(it.pit(), it.plist()))) {
2869 counters.step(layout.counter);
2870 par.params().labelString(
2871 par.expandLabel(layout, bp));
2873 par.params().labelString(docstring());
2876 case LABEL_ITEMIZE: {
2877 // At some point of time we should do something more
2878 // clever here, like:
2879 // par.params().labelString(
2880 // bp.user_defined_bullet(par.itemdepth).getText());
2881 // for now, use a simple hardcoded label
2882 docstring itemlabel;
2883 switch (par.itemdepth) {
2885 itemlabel = char_type(0x2022);
2888 itemlabel = char_type(0x2013);
2891 itemlabel = char_type(0x2217);
2894 itemlabel = char_type(0x2219); // or 0x00b7
2897 par.params().labelString(itemlabel);
2901 case LABEL_ENUMERATE: {
2902 // FIXME: Yes I know this is a really, really! bad solution
2904 docstring enumcounter = from_ascii("enum");
2906 switch (par.itemdepth) {
2915 enumcounter += "iv";
2918 // not a valid enumdepth...
2922 // Maybe we have to reset the enumeration counter.
2923 if (needEnumCounterReset(it))
2924 counters.reset(enumcounter);
2926 counters.step(enumcounter);
2930 switch (par.itemdepth) {
2932 format = N_("\\arabic{enumi}.");
2935 format = N_("(\\alph{enumii})");
2938 format = N_("\\roman{enumiii}.");
2941 format = N_("\\Alph{enumiv}.");
2944 // not a valid enumdepth...
2948 par.params().labelString(counters.counterLabel(
2949 par.translateIfPossible(from_ascii(format), bp)));
2954 case LABEL_SENSITIVE: {
2955 string const & type = counters.current_float();
2956 docstring full_label;
2958 full_label = buf.B_("Senseless!!! ");
2960 docstring name = buf.B_(textclass.floats().getType(type).name());
2961 if (counters.hasCounter(from_utf8(type))) {
2962 counters.step(from_utf8(type));
2963 full_label = bformat(from_ascii("%1$s %2$s:"),
2965 counters.theCounter(from_utf8(type)));
2967 full_label = bformat(from_ascii("%1$s #:"), name);
2969 par.params().labelString(full_label);
2973 case LABEL_NO_LABEL:
2974 par.params().labelString(docstring());
2978 case LABEL_TOP_ENVIRONMENT:
2979 case LABEL_CENTERED_TOP_ENVIRONMENT:
2982 par.params().labelString(
2983 par.translateIfPossible(layout.labelstring(), bp));
2989 void Buffer::updateLabels(ParIterator & parit) const
2991 LASSERT(parit.pit() == 0, /**/);
2993 // set the position of the text in the buffer to be able
2994 // to resolve macros in it. This has nothing to do with
2995 // labels, but by putting it here we avoid implementing
2996 // a whole bunch of traversal routines just for this call.
2997 parit.text()->setMacrocontextPosition(parit);
2999 depth_type maxdepth = 0;
3000 pit_type const lastpit = parit.lastpit();
3001 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
3002 // reduce depth if necessary
3003 parit->params().depth(min(parit->params().depth(), maxdepth));
3004 maxdepth = parit->getMaxDepthAfter();
3006 // set the counter for this paragraph
3007 setLabel(*this, parit);
3010 InsetList::const_iterator iit = parit->insetList().begin();
3011 InsetList::const_iterator end = parit->insetList().end();
3012 for (; iit != end; ++iit) {
3013 parit.pos() = iit->pos;
3014 iit->inset->updateLabels(parit);