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 theBufferList().releaseChild(this, const_cast<Buffer *>(it->first));
295 // clear references to children in macro tables
296 d->children_positions.clear();
297 d->position_to_children.clear();
299 if (!d->temppath.destroyDirectory()) {
300 Alert::warning(_("Could not remove temporary directory"),
301 bformat(_("Could not remove the temporary directory %1$s"),
302 from_utf8(d->temppath.absFilename())));
305 // Remove any previewed LaTeX snippets associated with this buffer.
306 thePreviews().removeLoader(*this);
312 void Buffer::changed() const
319 frontend::WorkAreaManager & Buffer::workAreaManager() const
321 LASSERT(d->wa_, /**/);
326 Text & Buffer::text() const
328 return d->inset->text();
332 Inset & Buffer::inset() const
338 BufferParams & Buffer::params()
344 BufferParams const & Buffer::params() const
350 ParagraphList & Buffer::paragraphs()
352 return text().paragraphs();
356 ParagraphList const & Buffer::paragraphs() const
358 return text().paragraphs();
362 LyXVC & Buffer::lyxvc()
368 LyXVC const & Buffer::lyxvc() const
374 string const Buffer::temppath() const
376 return d->temppath.absFilename();
380 TexRow & Buffer::texrow()
386 TexRow const & Buffer::texrow() const
392 TocBackend & Buffer::tocBackend() const
394 return d->toc_backend;
398 Undo & Buffer::undo()
404 string Buffer::latexName(bool const no_path) const
406 FileName latex_name = makeLatexName(d->filename);
407 return no_path ? latex_name.onlyFileName()
408 : latex_name.absFilename();
412 string Buffer::logName(LogType * type) const
414 string const filename = latexName(false);
416 if (filename.empty()) {
422 string const path = temppath();
424 FileName const fname(addName(temppath(),
425 onlyFilename(changeExtension(filename,
427 FileName const bname(
428 addName(path, onlyFilename(
429 changeExtension(filename,
430 formats.extension("literate") + ".out"))));
432 // If no Latex log or Build log is newer, show Build log
434 if (bname.exists() &&
435 (!fname.exists() || fname.lastModified() < bname.lastModified())) {
436 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
439 return bname.absFilename();
441 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
444 return fname.absFilename();
448 void Buffer::setReadonly(bool const flag)
450 if (d->read_only != flag) {
457 void Buffer::setFileName(string const & newfile)
459 d->filename = makeAbsPath(newfile);
460 setReadonly(d->filename.isReadOnly());
465 int Buffer::readHeader(Lexer & lex)
467 int unknown_tokens = 0;
469 int begin_header_line = -1;
471 // Initialize parameters that may be/go lacking in header:
472 params().branchlist().clear();
473 params().preamble.erase();
474 params().options.erase();
475 params().master.erase();
476 params().float_placement.erase();
477 params().paperwidth.erase();
478 params().paperheight.erase();
479 params().leftmargin.erase();
480 params().rightmargin.erase();
481 params().topmargin.erase();
482 params().bottommargin.erase();
483 params().headheight.erase();
484 params().headsep.erase();
485 params().footskip.erase();
486 params().columnsep.erase();
487 params().fontsCJK.erase();
488 params().listings_params.clear();
489 params().clearLayoutModules();
490 params().clearRemovedModules();
491 params().pdfoptions().clear();
493 for (int i = 0; i < 4; ++i) {
494 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
495 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
498 ErrorList & errorList = d->errorLists["Parse"];
507 if (token == "\\end_header")
511 if (token == "\\begin_header") {
512 begin_header_line = line;
516 LYXERR(Debug::PARSER, "Handling document header token: `"
519 string unknown = params().readToken(lex, token, d->filename.onlyPath());
520 if (!unknown.empty()) {
521 if (unknown[0] != '\\' && token == "\\textclass") {
522 Alert::warning(_("Unknown document class"),
523 bformat(_("Using the default document class, because the "
524 "class %1$s is unknown."), from_utf8(unknown)));
527 docstring const s = bformat(_("Unknown token: "
531 errorList.push_back(ErrorItem(_("Document header error"),
536 if (begin_header_line) {
537 docstring const s = _("\\begin_header is missing");
538 errorList.push_back(ErrorItem(_("Document header error"),
542 params().makeDocumentClass();
544 return unknown_tokens;
549 // changed to be public and have one parameter
550 // Returns true if "\end_document" is not read (Asger)
551 bool Buffer::readDocument(Lexer & lex)
553 ErrorList & errorList = d->errorLists["Parse"];
556 if (!lex.checkFor("\\begin_document")) {
557 docstring const s = _("\\begin_document is missing");
558 errorList.push_back(ErrorItem(_("Document header error"),
562 // we are reading in a brand new document
563 LASSERT(paragraphs().empty(), /**/);
567 if (params().outputChanges) {
568 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
569 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
570 LaTeXFeatures::isAvailable("xcolor");
572 if (!dvipost && !xcolorulem) {
573 Alert::warning(_("Changes not shown in LaTeX output"),
574 _("Changes will not be highlighted in LaTeX output, "
575 "because neither dvipost nor xcolor/ulem are installed.\n"
576 "Please install these packages or redefine "
577 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
578 } else if (!xcolorulem) {
579 Alert::warning(_("Changes not shown in LaTeX output"),
580 _("Changes will not be highlighted in LaTeX output "
581 "when using pdflatex, because xcolor and ulem are not installed.\n"
582 "Please install both packages or redefine "
583 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
587 if (!params().master.empty()) {
588 FileName const master_file = makeAbsPath(params().master,
589 onlyPath(absFileName()));
590 if (isLyXFilename(master_file.absFilename())) {
592 checkAndLoadLyXFile(master_file, true);
594 // set master as master buffer, but only
595 // if we are a real child
596 if (master->isChild(this))
598 // if the master is not fully loaded
599 // it is probably just loading this
600 // child. No warning needed then.
601 else if (master->isFullyLoaded())
602 LYXERR0("The master '"
604 << "' assigned to this document '"
606 << "' does not include "
607 "this document. Ignoring the master assignment.");
613 bool const res = text().read(*this, lex, errorList, d->inset);
616 updateMacroInstances();
621 // needed to insert the selection
622 void Buffer::insertStringAsLines(ParagraphList & pars,
623 pit_type & pit, pos_type & pos,
624 Font const & fn, docstring const & str, bool autobreakrows)
628 // insert the string, don't insert doublespace
629 bool space_inserted = true;
630 for (docstring::const_iterator cit = str.begin();
631 cit != str.end(); ++cit) {
632 Paragraph & par = pars[pit];
634 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
635 breakParagraph(params(), pars, pit, pos,
636 par.layout().isEnvironment());
639 space_inserted = true;
643 // do not insert consecutive spaces if !free_spacing
644 } else if ((*cit == ' ' || *cit == '\t') &&
645 space_inserted && !par.isFreeSpacing()) {
647 } else if (*cit == '\t') {
648 if (!par.isFreeSpacing()) {
649 // tabs are like spaces here
650 par.insertChar(pos, ' ', font, params().trackChanges);
652 space_inserted = true;
654 par.insertChar(pos, *cit, font, params().trackChanges);
656 space_inserted = true;
658 } else if (!isPrintable(*cit)) {
659 // Ignore unprintables
662 // just insert the character
663 par.insertChar(pos, *cit, font, params().trackChanges);
665 space_inserted = (*cit == ' ');
672 bool Buffer::readString(string const & s)
674 params().compressed = false;
676 // remove dummy empty par
677 paragraphs().clear();
681 FileName const name = FileName::tempName("Buffer_readString");
682 switch (readFile(lex, name, true)) {
686 // We need to call lyx2lyx, so write the input to a file
687 ofstream os(name.toFilesystemEncoding().c_str());
690 return readFile(name);
700 bool Buffer::readFile(FileName const & filename)
702 FileName fname(filename);
704 params().compressed = fname.isZippedFile();
706 // remove dummy empty par
707 paragraphs().clear();
710 if (readFile(lex, fname) != success)
717 bool Buffer::isFullyLoaded() const
719 return d->file_fully_loaded;
723 void Buffer::setFullyLoaded(bool value)
725 d->file_fully_loaded = value;
729 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
732 LASSERT(!filename.empty(), /**/);
734 // the first (non-comment) token _must_ be...
735 if (!lex.checkFor("\\lyxformat")) {
736 Alert::error(_("Document format failure"),
737 bformat(_("%1$s is not a readable LyX document."),
738 from_utf8(filename.absFilename())));
744 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
745 // if present remove ".," from string.
746 size_t dot = tmp_format.find_first_of(".,");
747 //lyxerr << " dot found at " << dot << endl;
748 if (dot != string::npos)
749 tmp_format.erase(dot, 1);
750 int const file_format = convert<int>(tmp_format);
751 //lyxerr << "format: " << file_format << endl;
753 // save timestamp and checksum of the original disk file, making sure
754 // to not overwrite them with those of the file created in the tempdir
755 // when it has to be converted to the current format.
757 // Save the timestamp and checksum of disk file. If filename is an
758 // emergency file, save the timestamp and checksum of the original lyx file
759 // because isExternallyModified will check for this file. (BUG4193)
760 string diskfile = filename.absFilename();
761 if (suffixIs(diskfile, ".emergency"))
762 diskfile = diskfile.substr(0, diskfile.size() - 10);
763 saveCheckSum(FileName(diskfile));
766 if (file_format != LYX_FORMAT) {
769 // lyx2lyx would fail
772 FileName const tmpfile = FileName::tempName("Buffer_readFile");
773 if (tmpfile.empty()) {
774 Alert::error(_("Conversion failed"),
775 bformat(_("%1$s is from a different"
776 " version of LyX, but a temporary"
777 " file for converting it could"
779 from_utf8(filename.absFilename())));
782 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
783 if (lyx2lyx.empty()) {
784 Alert::error(_("Conversion script not found"),
785 bformat(_("%1$s is from a different"
786 " version of LyX, but the"
787 " conversion script lyx2lyx"
788 " could not be found."),
789 from_utf8(filename.absFilename())));
792 ostringstream command;
793 command << os::python()
794 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
795 << " -t " << convert<string>(LYX_FORMAT)
796 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
797 << ' ' << quoteName(filename.toFilesystemEncoding());
798 string const command_str = command.str();
800 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
802 cmd_ret const ret = runCommand(command_str);
803 if (ret.first != 0) {
804 Alert::error(_("Conversion script failed"),
805 bformat(_("%1$s is from a different version"
806 " of LyX, but the lyx2lyx script"
807 " failed to convert it."),
808 from_utf8(filename.absFilename())));
811 bool const ret = readFile(tmpfile);
812 // Do stuff with tmpfile name and buffer name here.
813 return ret ? success : failure;
818 if (readDocument(lex)) {
819 Alert::error(_("Document format failure"),
820 bformat(_("%1$s ended unexpectedly, which means"
821 " that it is probably corrupted."),
822 from_utf8(filename.absFilename())));
825 d->file_fully_loaded = true;
830 // Should probably be moved to somewhere else: BufferView? LyXView?
831 bool Buffer::save() const
833 // We don't need autosaves in the immediate future. (Asger)
834 resetAutosaveTimers();
836 string const encodedFilename = d->filename.toFilesystemEncoding();
839 bool madeBackup = false;
841 // make a backup if the file already exists
842 if (lyxrc.make_backup && fileName().exists()) {
843 backupName = FileName(absFileName() + '~');
844 if (!lyxrc.backupdir_path.empty()) {
845 string const mangledName =
846 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
847 backupName = FileName(addName(lyxrc.backupdir_path,
850 if (fileName().copyTo(backupName)) {
853 Alert::error(_("Backup failure"),
854 bformat(_("Cannot create backup file %1$s.\n"
855 "Please check whether the directory exists and is writeable."),
856 from_utf8(backupName.absFilename())));
857 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
861 // ask if the disk file has been externally modified (use checksum method)
862 if (fileName().exists() && isExternallyModified(checksum_method)) {
863 docstring const file = makeDisplayPath(absFileName(), 20);
864 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
865 "you want to overwrite this file?"), file);
866 int const ret = Alert::prompt(_("Overwrite modified file?"),
867 text, 1, 1, _("&Overwrite"), _("&Cancel"));
872 if (writeFile(d->filename)) {
876 // Saving failed, so backup is not backup
878 backupName.moveTo(d->filename);
884 bool Buffer::writeFile(FileName const & fname) const
886 if (d->read_only && fname == d->filename)
891 docstring const str = bformat(_("Saving document %1$s..."),
892 makeDisplayPath(fname.absFilename()));
895 if (params().compressed) {
896 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
897 retval = ofs && write(ofs);
899 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
900 retval = ofs && write(ofs);
904 message(str + _(" could not write file!"));
908 removeAutosaveFile(d->filename.absFilename());
910 saveCheckSum(d->filename);
911 message(str + _(" done."));
917 bool Buffer::write(ostream & ofs) const
920 // Use the standard "C" locale for file output.
921 ofs.imbue(locale::classic());
924 // The top of the file should not be written by params().
926 // write out a comment in the top of the file
927 ofs << "#LyX " << lyx_version
928 << " created this file. For more info see http://www.lyx.org/\n"
929 << "\\lyxformat " << LYX_FORMAT << "\n"
930 << "\\begin_document\n";
932 /// For each author, set 'used' to true if there is a change
933 /// by this author in the document; otherwise set it to 'false'.
934 AuthorList::Authors::const_iterator a_it = params().authors().begin();
935 AuthorList::Authors::const_iterator a_end = params().authors().end();
936 for (; a_it != a_end; ++a_it)
937 a_it->second.setUsed(false);
939 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
940 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
941 for ( ; it != end; ++it)
942 it->checkAuthors(params().authors());
944 // now write out the buffer parameters.
945 ofs << "\\begin_header\n";
946 params().writeFile(ofs);
947 ofs << "\\end_header\n";
950 ofs << "\n\\begin_body\n";
951 text().write(*this, ofs);
952 ofs << "\n\\end_body\n";
954 // Write marker that shows file is complete
955 ofs << "\\end_document" << endl;
957 // Shouldn't really be needed....
960 // how to check if close went ok?
961 // Following is an attempt... (BE 20001011)
963 // good() returns false if any error occured, including some
965 // bad() returns true if something bad happened in the buffer,
966 // which should include file system full errors.
971 lyxerr << "File was not closed properly." << endl;
978 bool Buffer::makeLaTeXFile(FileName const & fname,
979 string const & original_path,
980 OutputParams const & runparams,
981 bool output_preamble, bool output_body) const
983 string const encoding = runparams.encoding->iconvName();
984 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
987 try { ofs.reset(encoding); }
988 catch (iconv_codecvt_facet_exception & e) {
989 lyxerr << "Caught iconv exception: " << e.what() << endl;
990 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
991 "verify that the support software for your encoding (%1$s) is "
992 "properly installed"), from_ascii(encoding)));
995 if (!openFileWrite(ofs, fname))
998 //TexStream ts(ofs.rdbuf(), &texrow());
999 ErrorList & errorList = d->errorLists["Export"];
1001 bool failed_export = false;
1004 writeLaTeXSource(ofs, original_path,
1005 runparams, output_preamble, output_body);
1007 catch (EncodingException & e) {
1008 odocstringstream ods;
1009 ods.put(e.failed_char);
1011 oss << "0x" << hex << e.failed_char << dec;
1012 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1013 " (code point %2$s)"),
1014 ods.str(), from_utf8(oss.str()));
1015 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1016 "representable in the chosen encoding.\n"
1017 "Changing the document encoding to utf8 could help."),
1018 e.par_id, e.pos, e.pos + 1));
1019 failed_export = true;
1021 catch (iconv_codecvt_facet_exception & e) {
1022 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1023 _(e.what()), -1, 0, 0));
1024 failed_export = true;
1026 catch (exception const & e) {
1027 errorList.push_back(ErrorItem(_("conversion failed"),
1028 _(e.what()), -1, 0, 0));
1029 failed_export = true;
1032 lyxerr << "Caught some really weird exception..." << endl;
1038 failed_export = true;
1039 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1043 return !failed_export;
1047 void Buffer::writeLaTeXSource(odocstream & os,
1048 string const & original_path,
1049 OutputParams const & runparams_in,
1050 bool const output_preamble, bool const output_body) const
1052 // The child documents, if any, shall be already loaded at this point.
1054 OutputParams runparams = runparams_in;
1056 // Classify the unicode characters appearing in math insets
1057 Encodings::initUnicodeMath(*this);
1059 // validate the buffer.
1060 LYXERR(Debug::LATEX, " Validating buffer...");
1061 LaTeXFeatures features(*this, params(), runparams);
1063 LYXERR(Debug::LATEX, " Buffer validation done.");
1065 // The starting paragraph of the coming rows is the
1066 // first paragraph of the document. (Asger)
1067 if (output_preamble && runparams.nice) {
1068 os << "%% LyX " << lyx_version << " created this file. "
1069 "For more info, see http://www.lyx.org/.\n"
1070 "%% Do not edit unless you really know what "
1072 d->texrow.newline();
1073 d->texrow.newline();
1075 LYXERR(Debug::INFO, "lyx document header finished");
1077 // Don't move this behind the parent_buffer=0 code below,
1078 // because then the macros will not get the right "redefinition"
1079 // flag as they don't see the parent macros which are output before.
1082 // fold macros if possible, still with parent buffer as the
1083 // macros will be put in the prefix anyway.
1084 updateMacroInstances();
1086 // There are a few differences between nice LaTeX and usual files:
1087 // usual is \batchmode and has a
1088 // special input@path to allow the including of figures
1089 // with either \input or \includegraphics (what figinsets do).
1090 // input@path is set when the actual parameter
1091 // original_path is set. This is done for usual tex-file, but not
1092 // for nice-latex-file. (Matthias 250696)
1093 // Note that input@path is only needed for something the user does
1094 // in the preamble, included .tex files or ERT, files included by
1095 // LyX work without it.
1096 if (output_preamble) {
1097 if (!runparams.nice) {
1098 // code for usual, NOT nice-latex-file
1099 os << "\\batchmode\n"; // changed
1100 // from \nonstopmode
1101 d->texrow.newline();
1103 if (!original_path.empty()) {
1105 // We don't know the encoding of inputpath
1106 docstring const inputpath = from_utf8(latex_path(original_path));
1107 os << "\\makeatletter\n"
1108 << "\\def\\input@path{{"
1109 << inputpath << "/}}\n"
1110 << "\\makeatother\n";
1111 d->texrow.newline();
1112 d->texrow.newline();
1113 d->texrow.newline();
1116 // get parent macros (if this buffer has a parent) which will be
1117 // written at the document begin further down.
1118 MacroSet parentMacros;
1119 listParentMacros(parentMacros, features);
1121 // Write the preamble
1122 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1124 runparams.use_japanese = features.isRequired("japanese");
1130 os << "\\begin{document}\n";
1131 d->texrow.newline();
1133 // output the parent macros
1134 MacroSet::iterator it = parentMacros.begin();
1135 MacroSet::iterator end = parentMacros.end();
1136 for (; it != end; ++it)
1137 (*it)->write(os, true);
1138 } // output_preamble
1140 d->texrow.start(paragraphs().begin()->id(), 0);
1142 LYXERR(Debug::INFO, "preamble finished, now the body.");
1144 // if we are doing a real file with body, even if this is the
1145 // child of some other buffer, let's cut the link here.
1146 // This happens for example if only a child document is printed.
1147 Buffer const * save_parent = 0;
1148 if (output_preamble) {
1149 save_parent = d->parent_buffer;
1150 d->parent_buffer = 0;
1154 latexParagraphs(*this, text(), os, d->texrow, runparams);
1156 // Restore the parenthood if needed
1157 if (output_preamble)
1158 d->parent_buffer = save_parent;
1160 // add this just in case after all the paragraphs
1162 d->texrow.newline();
1164 if (output_preamble) {
1165 os << "\\end{document}\n";
1166 d->texrow.newline();
1167 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1169 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1171 runparams_in.encoding = runparams.encoding;
1173 // Just to be sure. (Asger)
1174 d->texrow.newline();
1176 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1177 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1181 bool Buffer::isLatex() const
1183 return params().documentClass().outputType() == LATEX;
1187 bool Buffer::isLiterate() const
1189 return params().documentClass().outputType() == LITERATE;
1193 bool Buffer::isDocBook() const
1195 return params().documentClass().outputType() == DOCBOOK;
1199 void Buffer::makeDocBookFile(FileName const & fname,
1200 OutputParams const & runparams,
1201 bool const body_only) const
1203 LYXERR(Debug::LATEX, "makeDocBookFile...");
1206 if (!openFileWrite(ofs, fname))
1209 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1213 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1217 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1218 OutputParams const & runparams,
1219 bool const only_body) const
1221 LaTeXFeatures features(*this, params(), runparams);
1226 DocumentClass const & tclass = params().documentClass();
1227 string const top_element = tclass.latexname();
1230 if (runparams.flavor == OutputParams::XML)
1231 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1234 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1237 if (! tclass.class_header().empty())
1238 os << from_ascii(tclass.class_header());
1239 else if (runparams.flavor == OutputParams::XML)
1240 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1241 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1243 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1245 docstring preamble = from_utf8(params().preamble);
1246 if (runparams.flavor != OutputParams::XML ) {
1247 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1248 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1249 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1250 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1253 string const name = runparams.nice
1254 ? changeExtension(absFileName(), ".sgml") : fname;
1255 preamble += features.getIncludedFiles(name);
1256 preamble += features.getLyXSGMLEntities();
1258 if (!preamble.empty()) {
1259 os << "\n [ " << preamble << " ]";
1264 string top = top_element;
1266 if (runparams.flavor == OutputParams::XML)
1267 top += params().language->code();
1269 top += params().language->code().substr(0, 2);
1272 if (!params().options.empty()) {
1274 top += params().options;
1277 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1278 << " file was created by LyX " << lyx_version
1279 << "\n See http://www.lyx.org/ for more information -->\n";
1281 params().documentClass().counters().reset();
1285 sgml::openTag(os, top);
1287 docbookParagraphs(paragraphs(), *this, os, runparams);
1288 sgml::closeTag(os, top_element);
1292 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1293 // Other flags: -wall -v0 -x
1294 int Buffer::runChktex()
1298 // get LaTeX-Filename
1299 FileName const path(temppath());
1300 string const name = addName(path.absFilename(), latexName());
1301 string const org_path = filePath();
1303 PathChanger p(path); // path to LaTeX file
1304 message(_("Running chktex..."));
1306 // Generate the LaTeX file if neccessary
1307 OutputParams runparams(¶ms().encoding());
1308 runparams.flavor = OutputParams::LATEX;
1309 runparams.nice = false;
1310 makeLaTeXFile(FileName(name), org_path, runparams);
1313 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1314 int const res = chktex.run(terr); // run chktex
1317 Alert::error(_("chktex failure"),
1318 _("Could not run chktex successfully."));
1319 } else if (res > 0) {
1320 ErrorList & errlist = d->errorLists["ChkTeX"];
1322 bufferErrors(terr, errlist);
1333 void Buffer::validate(LaTeXFeatures & features) const
1335 params().validate(features);
1339 for_each(paragraphs().begin(), paragraphs().end(),
1340 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1342 if (lyxerr.debugging(Debug::LATEX)) {
1343 features.showStruct();
1348 void Buffer::getLabelList(vector<docstring> & list) const
1350 // If this is a child document, use the parent's list instead.
1351 if (d->parent_buffer) {
1352 d->parent_buffer->getLabelList(list);
1357 Toc & toc = d->toc_backend.toc("label");
1358 TocIterator toc_it = toc.begin();
1359 TocIterator end = toc.end();
1360 for (; toc_it != end; ++toc_it) {
1361 if (toc_it->depth() == 0)
1362 list.push_back(toc_it->str());
1367 void Buffer::updateBibfilesCache() const
1369 // If this is a child document, use the parent's cache instead.
1370 if (d->parent_buffer) {
1371 d->parent_buffer->updateBibfilesCache();
1375 d->bibfilesCache_.clear();
1376 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1377 if (it->lyxCode() == BIBTEX_CODE) {
1378 InsetBibtex const & inset =
1379 static_cast<InsetBibtex const &>(*it);
1380 support::FileNameList const bibfiles = inset.getBibFiles();
1381 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1384 } else if (it->lyxCode() == INCLUDE_CODE) {
1385 InsetInclude & inset =
1386 static_cast<InsetInclude &>(*it);
1387 inset.updateBibfilesCache();
1388 support::FileNameList const & bibfiles =
1389 inset.getBibfilesCache(*this);
1390 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1395 // the bibinfo cache is now invalid
1396 d->bibinfoCacheValid_ = false;
1400 void Buffer::invalidateBibinfoCache()
1402 d->bibinfoCacheValid_ = false;
1406 support::FileNameList const & Buffer::getBibfilesCache() const
1408 // If this is a child document, use the parent's cache instead.
1409 if (d->parent_buffer)
1410 return d->parent_buffer->getBibfilesCache();
1412 // We update the cache when first used instead of at loading time.
1413 if (d->bibfilesCache_.empty())
1414 const_cast<Buffer *>(this)->updateBibfilesCache();
1416 return d->bibfilesCache_;
1420 BiblioInfo const & Buffer::masterBibInfo() const
1422 // if this is a child document and the parent is already loaded
1423 // use the parent's list instead [ale990412]
1424 Buffer const * const tmp = masterBuffer();
1427 return tmp->masterBibInfo();
1428 return localBibInfo();
1432 BiblioInfo const & Buffer::localBibInfo() const
1434 if (d->bibinfoCacheValid_) {
1435 support::FileNameList const & bibfilesCache = getBibfilesCache();
1436 // compare the cached timestamps with the actual ones.
1437 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1438 support::FileNameList::const_iterator en = bibfilesCache.end();
1439 for (; ei != en; ++ ei) {
1440 time_t lastw = ei->lastModified();
1441 if (lastw != d->bibfileStatus_[*ei]) {
1442 d->bibinfoCacheValid_ = false;
1443 d->bibfileStatus_[*ei] = lastw;
1449 if (!d->bibinfoCacheValid_) {
1450 d->bibinfo_.clear();
1451 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1452 it->fillWithBibKeys(d->bibinfo_, it);
1453 d->bibinfoCacheValid_ = true;
1459 bool Buffer::isDepClean(string const & name) const
1461 DepClean::const_iterator const it = d->dep_clean.find(name);
1462 if (it == d->dep_clean.end())
1468 void Buffer::markDepClean(string const & name)
1470 d->dep_clean[name] = true;
1474 bool Buffer::dispatch(string const & command, bool * result)
1476 return dispatch(lyxaction.lookupFunc(command), result);
1480 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1482 bool dispatched = true;
1484 switch (func.action) {
1485 case LFUN_BUFFER_EXPORT: {
1486 bool const tmp = doExport(to_utf8(func.argument()), false);
1492 case LFUN_BRANCH_ACTIVATE:
1493 case LFUN_BRANCH_DEACTIVATE: {
1494 BranchList & branchList = params().branchlist();
1495 docstring const branchName = func.argument();
1496 Branch * branch = branchList.find(branchName);
1498 LYXERR0("Branch " << branchName << " does not exist.");
1500 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1512 void Buffer::changeLanguage(Language const * from, Language const * to)
1514 LASSERT(from, /**/);
1517 for_each(par_iterator_begin(),
1519 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1523 bool Buffer::isMultiLingual() const
1525 ParConstIterator end = par_iterator_end();
1526 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1527 if (it->isMultiLingual(params()))
1534 DocIterator Buffer::getParFromID(int const id) const
1536 Buffer * buf = const_cast<Buffer *>(this);
1538 // John says this is called with id == -1 from undo
1539 lyxerr << "getParFromID(), id: " << id << endl;
1540 return doc_iterator_end(buf);
1543 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
1544 if (it.paragraph().id() == id)
1547 return doc_iterator_end(buf);
1551 bool Buffer::hasParWithID(int const id) const
1553 return !getParFromID(id).atEnd();
1557 ParIterator Buffer::par_iterator_begin()
1559 return ParIterator(doc_iterator_begin(this));
1563 ParIterator Buffer::par_iterator_end()
1565 return ParIterator(doc_iterator_end(this));
1569 ParConstIterator Buffer::par_iterator_begin() const
1571 return ParConstIterator(doc_iterator_begin(this));
1575 ParConstIterator Buffer::par_iterator_end() const
1577 return ParConstIterator(doc_iterator_end(this));
1581 Language const * Buffer::language() const
1583 return params().language;
1587 docstring const Buffer::B_(string const & l10n) const
1589 return params().B_(l10n);
1593 bool Buffer::isClean() const
1595 return d->lyx_clean;
1599 bool Buffer::isBakClean() const
1601 return d->bak_clean;
1605 bool Buffer::isExternallyModified(CheckMethod method) const
1607 LASSERT(d->filename.exists(), /**/);
1608 // if method == timestamp, check timestamp before checksum
1609 return (method == checksum_method
1610 || d->timestamp_ != d->filename.lastModified())
1611 && d->checksum_ != d->filename.checksum();
1615 void Buffer::saveCheckSum(FileName const & file) const
1617 if (file.exists()) {
1618 d->timestamp_ = file.lastModified();
1619 d->checksum_ = file.checksum();
1621 // in the case of save to a new file.
1628 void Buffer::markClean() const
1630 if (!d->lyx_clean) {
1631 d->lyx_clean = true;
1634 // if the .lyx file has been saved, we don't need an
1636 d->bak_clean = true;
1640 void Buffer::markBakClean() const
1642 d->bak_clean = true;
1646 void Buffer::setUnnamed(bool flag)
1652 bool Buffer::isUnnamed() const
1658 // FIXME: this function should be moved to buffer_pimpl.C
1659 void Buffer::markDirty()
1662 d->lyx_clean = false;
1665 d->bak_clean = false;
1667 DepClean::iterator it = d->dep_clean.begin();
1668 DepClean::const_iterator const end = d->dep_clean.end();
1670 for (; it != end; ++it)
1675 FileName Buffer::fileName() const
1681 string Buffer::absFileName() const
1683 return d->filename.absFilename();
1687 string Buffer::filePath() const
1689 return d->filename.onlyPath().absFilename() + "/";
1693 bool Buffer::isReadonly() const
1695 return d->read_only;
1699 void Buffer::setParent(Buffer const * buffer)
1701 // Avoids recursive include.
1702 d->parent_buffer = buffer == this ? 0 : buffer;
1707 Buffer const * Buffer::parent() const
1709 return d->parent_buffer;
1713 void Buffer::collectRelatives(BufferSet & bufs) const
1717 parent()->collectRelatives(bufs);
1719 // loop over children
1720 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
1721 Impl::BufferPositionMap::iterator end = d->children_positions.end();
1722 for (; it != end; ++it)
1723 bufs.insert(const_cast<Buffer *>(it->first));
1727 std::vector<Buffer const *> Buffer::allRelatives() const
1730 collectRelatives(bufs);
1731 BufferSet::iterator it = bufs.begin();
1732 std::vector<Buffer const *> ret;
1733 for (; it != bufs.end(); ++it)
1739 Buffer const * Buffer::masterBuffer() const
1741 if (!d->parent_buffer)
1744 return d->parent_buffer->masterBuffer();
1748 bool Buffer::isChild(Buffer * child) const
1750 return d->children_positions.find(child) != d->children_positions.end();
1754 DocIterator Buffer::firstChildPosition(Buffer const * child)
1756 Impl::BufferPositionMap::iterator it;
1757 it = d->children_positions.find(child);
1758 if (it == d->children_positions.end())
1759 return DocIterator(this);
1764 template<typename M>
1765 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
1770 typename M::iterator it = m.lower_bound(x);
1771 if (it == m.begin())
1779 MacroData const * Buffer::getBufferMacro(docstring const & name,
1780 DocIterator const & pos) const
1782 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
1784 // if paragraphs have no macro context set, pos will be empty
1788 // we haven't found anything yet
1789 DocIterator bestPos = par_iterator_begin();
1790 MacroData const * bestData = 0;
1792 // find macro definitions for name
1793 Impl::NamePositionScopeMacroMap::iterator nameIt
1794 = d->macros.find(name);
1795 if (nameIt != d->macros.end()) {
1796 // find last definition in front of pos or at pos itself
1797 Impl::PositionScopeMacroMap::const_iterator it
1798 = greatest_below(nameIt->second, pos);
1799 if (it != nameIt->second.end()) {
1801 // scope ends behind pos?
1802 if (pos < it->second.first) {
1803 // Looks good, remember this. If there
1804 // is no external macro behind this,
1805 // we found the right one already.
1806 bestPos = it->first;
1807 bestData = &it->second.second;
1811 // try previous macro if there is one
1812 if (it == nameIt->second.begin())
1819 // find macros in included files
1820 Impl::PositionScopeBufferMap::const_iterator it
1821 = greatest_below(d->position_to_children, pos);
1822 if (it == d->position_to_children.end())
1823 // no children before
1827 // do we know something better (i.e. later) already?
1828 if (it->first < bestPos )
1831 // scope ends behind pos?
1832 if (pos < it->second.first) {
1833 // look for macro in external file
1834 d->macro_lock = true;
1835 MacroData const * data
1836 = it->second.second->getMacro(name, false);
1837 d->macro_lock = false;
1839 bestPos = it->first;
1845 // try previous file if there is one
1846 if (it == d->position_to_children.begin())
1851 // return the best macro we have found
1856 MacroData const * Buffer::getMacro(docstring const & name,
1857 DocIterator const & pos, bool global) const
1862 // query buffer macros
1863 MacroData const * data = getBufferMacro(name, pos);
1867 // If there is a master buffer, query that
1868 if (d->parent_buffer) {
1869 d->macro_lock = true;
1870 MacroData const * macro = d->parent_buffer->getMacro(
1871 name, *this, false);
1872 d->macro_lock = false;
1878 data = MacroTable::globalMacros().get(name);
1887 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
1889 // set scope end behind the last paragraph
1890 DocIterator scope = par_iterator_begin();
1891 scope.pit() = scope.lastpit() + 1;
1893 return getMacro(name, scope, global);
1897 MacroData const * Buffer::getMacro(docstring const & name,
1898 Buffer const & child, bool global) const
1900 // look where the child buffer is included first
1901 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
1902 if (it == d->children_positions.end())
1905 // check for macros at the inclusion position
1906 return getMacro(name, it->second, global);
1910 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
1912 pit_type lastpit = it.lastpit();
1914 // look for macros in each paragraph
1915 while (it.pit() <= lastpit) {
1916 Paragraph & par = it.paragraph();
1918 // iterate over the insets of the current paragraph
1919 InsetList const & insets = par.insetList();
1920 InsetList::const_iterator iit = insets.begin();
1921 InsetList::const_iterator end = insets.end();
1922 for (; iit != end; ++iit) {
1923 it.pos() = iit->pos;
1925 // is it a nested text inset?
1926 if (iit->inset->asInsetText()) {
1927 // Inset needs its own scope?
1928 InsetText const * itext
1929 = iit->inset->asInsetText();
1930 bool newScope = itext->isMacroScope();
1932 // scope which ends just behind the inset
1933 DocIterator insetScope = it;
1936 // collect macros in inset
1937 it.push_back(CursorSlice(*iit->inset));
1938 updateMacros(it, newScope ? insetScope : scope);
1943 // is it an external file?
1944 if (iit->inset->lyxCode() == INCLUDE_CODE) {
1945 // get buffer of external file
1946 InsetInclude const & inset
1947 = static_cast<InsetInclude const &>(*iit->inset);
1948 d->macro_lock = true;
1949 Buffer * child = inset.loadIfNeeded(*this);
1950 d->macro_lock = false;
1954 // register its position, but only when it is
1955 // included first in the buffer
1956 if (d->children_positions.find(child)
1957 == d->children_positions.end())
1958 d->children_positions[child] = it;
1960 // register child with its scope
1961 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
1965 if (iit->inset->lyxCode() != MATHMACRO_CODE)
1969 MathMacroTemplate & macroTemplate
1970 = static_cast<MathMacroTemplate &>(*iit->inset);
1971 MacroContext mc(*this, it);
1972 macroTemplate.updateToContext(mc);
1975 bool valid = macroTemplate.validMacro();
1976 // FIXME: Should be fixNameAndCheckIfValid() in fact,
1977 // then the BufferView's cursor will be invalid in
1978 // some cases which leads to crashes.
1983 d->macros[macroTemplate.name()][it] =
1984 Impl::ScopeMacro(scope, MacroData(*this, it));
1994 void Buffer::updateMacros() const
1999 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2001 // start with empty table
2003 d->children_positions.clear();
2004 d->position_to_children.clear();
2006 // Iterate over buffer, starting with first paragraph
2007 // The scope must be bigger than any lookup DocIterator
2008 // later. For the global lookup, lastpit+1 is used, hence
2009 // we use lastpit+2 here.
2010 DocIterator it = par_iterator_begin();
2011 DocIterator outerScope = it;
2012 outerScope.pit() = outerScope.lastpit() + 2;
2013 updateMacros(it, outerScope);
2017 void Buffer::updateMacroInstances() const
2019 LYXERR(Debug::MACROS, "updateMacroInstances for "
2020 << d->filename.onlyFileName());
2021 DocIterator it = doc_iterator_begin(this);
2022 DocIterator end = doc_iterator_end(this);
2023 for (; it != end; it.forwardPos()) {
2024 // look for MathData cells in InsetMathNest insets
2025 Inset * inset = it.nextInset();
2029 InsetMath * minset = inset->asInsetMath();
2033 // update macro in all cells of the InsetMathNest
2034 DocIterator::idx_type n = minset->nargs();
2035 MacroContext mc = MacroContext(*this, it);
2036 for (DocIterator::idx_type i = 0; i < n; ++i) {
2037 MathData & data = minset->cell(i);
2038 data.updateMacros(0, mc);
2044 void Buffer::listMacroNames(MacroNameSet & macros) const
2049 d->macro_lock = true;
2051 // loop over macro names
2052 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2053 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2054 for (; nameIt != nameEnd; ++nameIt)
2055 macros.insert(nameIt->first);
2057 // loop over children
2058 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2059 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2060 for (; it != end; ++it)
2061 it->first->listMacroNames(macros);
2064 if (d->parent_buffer)
2065 d->parent_buffer->listMacroNames(macros);
2067 d->macro_lock = false;
2071 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2073 if (!d->parent_buffer)
2077 d->parent_buffer->listMacroNames(names);
2080 MacroNameSet::iterator it = names.begin();
2081 MacroNameSet::iterator end = names.end();
2082 for (; it != end; ++it) {
2084 MacroData const * data =
2085 d->parent_buffer->getMacro(*it, *this, false);
2087 macros.insert(data);
2089 // we cannot access the original MathMacroTemplate anymore
2090 // here to calls validate method. So we do its work here manually.
2091 // FIXME: somehow make the template accessible here.
2092 if (data->optionals() > 0)
2093 features.require("xargs");
2099 Buffer::References & Buffer::references(docstring const & label)
2101 if (d->parent_buffer)
2102 return const_cast<Buffer *>(masterBuffer())->references(label);
2104 RefCache::iterator it = d->ref_cache_.find(label);
2105 if (it != d->ref_cache_.end())
2106 return it->second.second;
2108 static InsetLabel const * dummy_il = 0;
2109 static References const dummy_refs;
2110 it = d->ref_cache_.insert(
2111 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2112 return it->second.second;
2116 Buffer::References const & Buffer::references(docstring const & label) const
2118 return const_cast<Buffer *>(this)->references(label);
2122 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2124 masterBuffer()->d->ref_cache_[label].first = il;
2128 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2130 return masterBuffer()->d->ref_cache_[label].first;
2134 void Buffer::clearReferenceCache() const
2136 if (!d->parent_buffer)
2137 d->ref_cache_.clear();
2141 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2144 //FIXME: This does not work for child documents yet.
2145 LASSERT(code == CITE_CODE, /**/);
2146 // Check if the label 'from' appears more than once
2147 vector<docstring> labels;
2149 BiblioInfo const & keys = masterBibInfo();
2150 BiblioInfo::const_iterator bit = keys.begin();
2151 BiblioInfo::const_iterator bend = keys.end();
2153 for (; bit != bend; ++bit)
2155 labels.push_back(bit->first);
2158 if (count(labels.begin(), labels.end(), from) > 1)
2161 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2162 if (it->lyxCode() == code) {
2163 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2164 docstring const oldValue = inset.getParam(paramName);
2165 if (oldValue == from)
2166 inset.setParam(paramName, to);
2172 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2173 pit_type par_end, bool full_source) const
2175 OutputParams runparams(¶ms().encoding());
2176 runparams.nice = true;
2177 runparams.flavor = OutputParams::LATEX;
2178 runparams.linelen = lyxrc.plaintext_linelen;
2179 // No side effect of file copying and image conversion
2180 runparams.dryrun = true;
2184 os << "% " << _("Preview source code") << "\n\n";
2185 d->texrow.newline();
2186 d->texrow.newline();
2188 writeDocBookSource(os, absFileName(), runparams, false);
2190 // latex or literate
2191 writeLaTeXSource(os, string(), runparams, true, true);
2193 runparams.par_begin = par_begin;
2194 runparams.par_end = par_end;
2195 if (par_begin + 1 == par_end) {
2197 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2201 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2202 convert<docstring>(par_begin),
2203 convert<docstring>(par_end - 1))
2206 d->texrow.newline();
2207 d->texrow.newline();
2208 // output paragraphs
2210 docbookParagraphs(paragraphs(), *this, os, runparams);
2212 // latex or literate
2213 latexParagraphs(*this, text(), os, d->texrow, runparams);
2218 ErrorList & Buffer::errorList(string const & type) const
2220 static ErrorList emptyErrorList;
2221 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2222 if (I == d->errorLists.end())
2223 return emptyErrorList;
2229 void Buffer::updateTocItem(std::string const & type,
2230 DocIterator const & dit) const
2233 gui_->updateTocItem(type, dit);
2237 void Buffer::structureChanged() const
2240 gui_->structureChanged();
2244 void Buffer::errors(string const & err) const
2251 void Buffer::message(docstring const & msg) const
2258 void Buffer::setBusy(bool on) const
2265 void Buffer::setReadOnly(bool on) const
2268 d->wa_->setReadOnly(on);
2272 void Buffer::updateTitles() const
2275 d->wa_->updateTitles();
2279 void Buffer::resetAutosaveTimers() const
2282 gui_->resetAutosaveTimers();
2286 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2295 class AutoSaveBuffer : public ForkedProcess {
2298 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2299 : buffer_(buffer), fname_(fname) {}
2301 virtual boost::shared_ptr<ForkedProcess> clone() const
2303 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2308 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2309 from_utf8(fname_.absFilename())));
2310 return run(DontWait);
2314 virtual int generateChild();
2316 Buffer const & buffer_;
2321 int AutoSaveBuffer::generateChild()
2323 // tmp_ret will be located (usually) in /tmp
2324 // will that be a problem?
2325 // Note that this calls ForkedCalls::fork(), so it's
2326 // ok cross-platform.
2327 pid_t const pid = fork();
2328 // If you want to debug the autosave
2329 // you should set pid to -1, and comment out the fork.
2330 if (pid != 0 && pid != -1)
2333 // pid = -1 signifies that lyx was unable
2334 // to fork. But we will do the save
2336 bool failed = false;
2337 FileName const tmp_ret = FileName::tempName("lyxauto");
2338 if (!tmp_ret.empty()) {
2339 buffer_.writeFile(tmp_ret);
2340 // assume successful write of tmp_ret
2341 if (!tmp_ret.moveTo(fname_))
2347 // failed to write/rename tmp_ret so try writing direct
2348 if (!buffer_.writeFile(fname_)) {
2349 // It is dangerous to do this in the child,
2350 // but safe in the parent, so...
2351 if (pid == -1) // emit message signal.
2352 buffer_.message(_("Autosave failed!"));
2356 if (pid == 0) // we are the child so...
2365 // Perfect target for a thread...
2366 void Buffer::autoSave() const
2368 if (isBakClean() || isReadonly()) {
2369 // We don't save now, but we'll try again later
2370 resetAutosaveTimers();
2374 // emit message signal.
2375 message(_("Autosaving current document..."));
2377 // create autosave filename
2378 string fname = filePath();
2380 fname += d->filename.onlyFileName();
2383 AutoSaveBuffer autosave(*this, FileName(fname));
2387 resetAutosaveTimers();
2391 string Buffer::bufferFormat() const
2397 if (params().encoding().package() == Encoding::japanese)
2403 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2404 string & result_file) const
2406 string backend_format;
2407 OutputParams runparams(¶ms().encoding());
2408 runparams.flavor = OutputParams::LATEX;
2409 runparams.linelen = lyxrc.plaintext_linelen;
2410 vector<string> backs = backends();
2411 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2412 // Get shortest path to format
2413 Graph::EdgePath path;
2414 for (vector<string>::const_iterator it = backs.begin();
2415 it != backs.end(); ++it) {
2416 Graph::EdgePath p = theConverters().getPath(*it, format);
2417 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2418 backend_format = *it;
2423 runparams.flavor = theConverters().getFlavor(path);
2425 Alert::error(_("Couldn't export file"),
2426 bformat(_("No information for exporting the format %1$s."),
2427 formats.prettyName(format)));
2431 backend_format = format;
2432 // FIXME: Don't hardcode format names here, but use a flag
2433 if (backend_format == "pdflatex")
2434 runparams.flavor = OutputParams::PDFLATEX;
2437 string filename = latexName(false);
2438 filename = addName(temppath(), filename);
2439 filename = changeExtension(filename,
2440 formats.extension(backend_format));
2443 updateMacroInstances();
2445 // Plain text backend
2446 if (backend_format == "text")
2447 writePlaintextFile(*this, FileName(filename), runparams);
2449 else if (backend_format == "lyx")
2450 writeFile(FileName(filename));
2452 else if (isDocBook()) {
2453 runparams.nice = !put_in_tempdir;
2454 makeDocBookFile(FileName(filename), runparams);
2457 else if (backend_format == format) {
2458 runparams.nice = true;
2459 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2461 } else if (!lyxrc.tex_allows_spaces
2462 && contains(filePath(), ' ')) {
2463 Alert::error(_("File name error"),
2464 _("The directory path to the document cannot contain spaces."));
2467 runparams.nice = false;
2468 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2472 string const error_type = (format == "program")
2473 ? "Build" : bufferFormat();
2474 ErrorList & error_list = d->errorLists[error_type];
2475 string const ext = formats.extension(format);
2476 FileName const tmp_result_file(changeExtension(filename, ext));
2477 bool const success = theConverters().convert(this, FileName(filename),
2478 tmp_result_file, FileName(absFileName()), backend_format, format,
2480 // Emit the signal to show the error list.
2481 if (format != backend_format)
2486 if (put_in_tempdir) {
2487 result_file = tmp_result_file.absFilename();
2491 result_file = changeExtension(absFileName(), ext);
2492 // We need to copy referenced files (e. g. included graphics
2493 // if format == "dvi") to the result dir.
2494 vector<ExportedFile> const files =
2495 runparams.exportdata->externalFiles(format);
2496 string const dest = onlyPath(result_file);
2497 CopyStatus status = SUCCESS;
2498 for (vector<ExportedFile>::const_iterator it = files.begin();
2499 it != files.end() && status != CANCEL; ++it) {
2500 string const fmt = formats.getFormatFromFile(it->sourceName);
2501 status = copyFile(fmt, it->sourceName,
2502 makeAbsPath(it->exportName, dest),
2503 it->exportName, status == FORCE);
2505 if (status == CANCEL) {
2506 message(_("Document export cancelled."));
2507 } else if (tmp_result_file.exists()) {
2508 // Finally copy the main file
2509 status = copyFile(format, tmp_result_file,
2510 FileName(result_file), result_file,
2512 message(bformat(_("Document exported as %1$s "
2514 formats.prettyName(format),
2515 makeDisplayPath(result_file)));
2517 // This must be a dummy converter like fax (bug 1888)
2518 message(bformat(_("Document exported as %1$s"),
2519 formats.prettyName(format)));
2526 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2529 return doExport(format, put_in_tempdir, result_file);
2533 bool Buffer::preview(string const & format) const
2536 if (!doExport(format, true, result_file))
2538 return formats.view(*this, FileName(result_file), format);
2542 bool Buffer::isExportable(string const & format) const
2544 vector<string> backs = backends();
2545 for (vector<string>::const_iterator it = backs.begin();
2546 it != backs.end(); ++it)
2547 if (theConverters().isReachable(*it, format))
2553 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2555 vector<string> backs = backends();
2556 vector<Format const *> result =
2557 theConverters().getReachable(backs[0], only_viewable, true);
2558 for (vector<string>::const_iterator it = backs.begin() + 1;
2559 it != backs.end(); ++it) {
2560 vector<Format const *> r =
2561 theConverters().getReachable(*it, only_viewable, false);
2562 result.insert(result.end(), r.begin(), r.end());
2568 vector<string> Buffer::backends() const
2571 if (params().baseClass()->isTeXClassAvailable()) {
2572 v.push_back(bufferFormat());
2573 // FIXME: Don't hardcode format names here, but use a flag
2574 if (v.back() == "latex")
2575 v.push_back("pdflatex");
2577 v.push_back("text");
2583 bool Buffer::readFileHelper(FileName const & s)
2585 // File information about normal file
2587 docstring const file = makeDisplayPath(s.absFilename(), 50);
2588 docstring text = bformat(_("The specified document\n%1$s"
2589 "\ncould not be read."), file);
2590 Alert::error(_("Could not read document"), text);
2594 // Check if emergency save file exists and is newer.
2595 FileName const e(s.absFilename() + ".emergency");
2597 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2598 docstring const file = makeDisplayPath(s.absFilename(), 20);
2599 docstring const text =
2600 bformat(_("An emergency save of the document "
2602 "Recover emergency save?"), file);
2603 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2604 _("&Recover"), _("&Load Original"),
2608 // the file is not saved if we load the emergency file.
2618 // Now check if autosave file is newer.
2619 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2621 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2622 docstring const file = makeDisplayPath(s.absFilename(), 20);
2623 docstring const text =
2624 bformat(_("The backup of the document "
2625 "%1$s is newer.\n\nLoad the "
2626 "backup instead?"), file);
2627 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2628 _("&Load backup"), _("Load &original"),
2632 // the file is not saved if we load the autosave file.
2636 // Here we delete the autosave
2647 bool Buffer::loadLyXFile(FileName const & s)
2649 if (s.isReadableFile()) {
2650 if (readFileHelper(s)) {
2651 lyxvc().file_found_hook(s);
2652 if (!s.isWritable())
2657 docstring const file = makeDisplayPath(s.absFilename(), 20);
2658 // Here we probably should run
2659 if (LyXVC::file_not_found_hook(s)) {
2660 docstring const text =
2661 bformat(_("Do you want to retrieve the document"
2662 " %1$s from version control?"), file);
2663 int const ret = Alert::prompt(_("Retrieve from version control?"),
2664 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2667 // How can we know _how_ to do the checkout?
2668 // With the current VC support it has to be,
2669 // a RCS file since CVS do not have special ,v files.
2671 return loadLyXFile(s);
2679 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2681 TeXErrors::Errors::const_iterator cit = terr.begin();
2682 TeXErrors::Errors::const_iterator end = terr.end();
2684 for (; cit != end; ++cit) {
2687 int errorRow = cit->error_in_line;
2688 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2694 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2695 } while (found && id_start == id_end && pos_start == pos_end);
2697 errorList.push_back(ErrorItem(cit->error_desc,
2698 cit->error_text, id_start, pos_start, pos_end));
2703 void Buffer::updateLabels(bool childonly) const
2705 // Use the master text class also for child documents
2706 Buffer const * const master = masterBuffer();
2707 DocumentClass const & textclass = master->params().documentClass();
2709 // keep the buffers to be children in this set. If the call from the
2710 // master comes back we can see which of them were actually seen (i.e.
2711 // via an InsetInclude). The remaining ones in the set need still be updated.
2712 static std::set<Buffer const *> bufToUpdate;
2714 // If this is a child document start with the master
2715 if (master != this) {
2716 bufToUpdate.insert(this);
2717 master->updateLabels(false);
2719 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
2720 if (bufToUpdate.find(this) == bufToUpdate.end())
2724 // start over the counters in the master
2725 textclass.counters().reset();
2728 // update will be done below for this buffer
2729 bufToUpdate.erase(this);
2731 // update all caches
2732 clearReferenceCache();
2733 inset().setBuffer(const_cast<Buffer &>(*this));
2736 Buffer & cbuf = const_cast<Buffer &>(*this);
2738 LASSERT(!text().paragraphs().empty(), /**/);
2741 ParIterator parit = cbuf.par_iterator_begin();
2742 updateLabels(parit);
2745 // TocBackend update will be done later.
2748 cbuf.tocBackend().update();
2750 cbuf.structureChanged();
2754 static depth_type getDepth(DocIterator const & it)
2756 depth_type depth = 0;
2757 for (size_t i = 0 ; i < it.depth() ; ++i)
2758 if (!it[i].inset().inMathed())
2759 depth += it[i].paragraph().getDepth() + 1;
2760 // remove 1 since the outer inset does not count
2764 static depth_type getItemDepth(ParIterator const & it)
2766 Paragraph const & par = *it;
2767 LabelType const labeltype = par.layout().labeltype;
2769 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
2772 // this will hold the lowest depth encountered up to now.
2773 depth_type min_depth = getDepth(it);
2774 ParIterator prev_it = it;
2777 --prev_it.top().pit();
2779 // start of nested inset: go to outer par
2781 if (prev_it.empty()) {
2782 // start of document: nothing to do
2787 // We search for the first paragraph with same label
2788 // that is not more deeply nested.
2789 Paragraph & prev_par = *prev_it;
2790 depth_type const prev_depth = getDepth(prev_it);
2791 if (labeltype == prev_par.layout().labeltype) {
2792 if (prev_depth < min_depth)
2793 return prev_par.itemdepth + 1;
2794 if (prev_depth == min_depth)
2795 return prev_par.itemdepth;
2797 min_depth = min(min_depth, prev_depth);
2798 // small optimization: if we are at depth 0, we won't
2799 // find anything else
2800 if (prev_depth == 0)
2806 static bool needEnumCounterReset(ParIterator const & it)
2808 Paragraph const & par = *it;
2809 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
2810 depth_type const cur_depth = par.getDepth();
2811 ParIterator prev_it = it;
2812 while (prev_it.pit()) {
2813 --prev_it.top().pit();
2814 Paragraph const & prev_par = *prev_it;
2815 if (prev_par.getDepth() <= cur_depth)
2816 return prev_par.layout().labeltype != LABEL_ENUMERATE;
2818 // start of nested inset: reset
2823 // set the label of a paragraph. This includes the counters.
2824 static void setLabel(Buffer const & buf, ParIterator & it)
2826 BufferParams const & bp = buf.masterBuffer()->params();
2827 DocumentClass const & textclass = bp.documentClass();
2828 Paragraph & par = it.paragraph();
2829 Layout const & layout = par.layout();
2830 Counters & counters = textclass.counters();
2832 if (par.params().startOfAppendix()) {
2833 // FIXME: only the counter corresponding to toplevel
2834 // sectionning should be reset
2836 counters.appendix(true);
2838 par.params().appendix(counters.appendix());
2840 // Compute the item depth of the paragraph
2841 par.itemdepth = getItemDepth(it);
2843 if (layout.margintype == MARGIN_MANUAL) {
2844 if (par.params().labelWidthString().empty())
2845 par.params().labelWidthString(par.translateIfPossible(layout.labelstring(), bp));
2847 par.params().labelWidthString(docstring());
2850 switch(layout.labeltype) {
2852 if (layout.toclevel <= bp.secnumdepth
2853 && (layout.latextype != LATEX_ENVIRONMENT
2854 || isFirstInSequence(it.pit(), it.plist()))) {
2855 counters.step(layout.counter);
2856 par.params().labelString(
2857 par.expandLabel(layout, bp));
2859 par.params().labelString(docstring());
2862 case LABEL_ITEMIZE: {
2863 // At some point of time we should do something more
2864 // clever here, like:
2865 // par.params().labelString(
2866 // bp.user_defined_bullet(par.itemdepth).getText());
2867 // for now, use a simple hardcoded label
2868 docstring itemlabel;
2869 switch (par.itemdepth) {
2871 itemlabel = char_type(0x2022);
2874 itemlabel = char_type(0x2013);
2877 itemlabel = char_type(0x2217);
2880 itemlabel = char_type(0x2219); // or 0x00b7
2883 par.params().labelString(itemlabel);
2887 case LABEL_ENUMERATE: {
2888 // FIXME: Yes I know this is a really, really! bad solution
2890 docstring enumcounter = from_ascii("enum");
2892 switch (par.itemdepth) {
2901 enumcounter += "iv";
2904 // not a valid enumdepth...
2908 // Maybe we have to reset the enumeration counter.
2909 if (needEnumCounterReset(it))
2910 counters.reset(enumcounter);
2912 counters.step(enumcounter);
2916 switch (par.itemdepth) {
2918 format = N_("\\arabic{enumi}.");
2921 format = N_("(\\alph{enumii})");
2924 format = N_("\\roman{enumiii}.");
2927 format = N_("\\Alph{enumiv}.");
2930 // not a valid enumdepth...
2934 par.params().labelString(counters.counterLabel(
2935 par.translateIfPossible(from_ascii(format), bp)));
2940 case LABEL_SENSITIVE: {
2941 string const & type = counters.current_float();
2942 docstring full_label;
2944 full_label = buf.B_("Senseless!!! ");
2946 docstring name = buf.B_(textclass.floats().getType(type).name());
2947 if (counters.hasCounter(from_utf8(type))) {
2948 counters.step(from_utf8(type));
2949 full_label = bformat(from_ascii("%1$s %2$s:"),
2951 counters.theCounter(from_utf8(type)));
2953 full_label = bformat(from_ascii("%1$s #:"), name);
2955 par.params().labelString(full_label);
2959 case LABEL_NO_LABEL:
2960 par.params().labelString(docstring());
2964 case LABEL_TOP_ENVIRONMENT:
2965 case LABEL_CENTERED_TOP_ENVIRONMENT:
2968 par.params().labelString(
2969 par.translateIfPossible(layout.labelstring(), bp));
2975 void Buffer::updateLabels(ParIterator & parit) const
2977 LASSERT(parit.pit() == 0, /**/);
2979 // set the position of the text in the buffer to be able
2980 // to resolve macros in it. This has nothing to do with
2981 // labels, but by putting it here we avoid implementing
2982 // a whole bunch of traversal routines just for this call.
2983 parit.text()->setMacrocontextPosition(parit);
2985 depth_type maxdepth = 0;
2986 pit_type const lastpit = parit.lastpit();
2987 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
2988 // reduce depth if necessary
2989 parit->params().depth(min(parit->params().depth(), maxdepth));
2990 maxdepth = parit->getMaxDepthAfter();
2992 // set the counter for this paragraph
2993 setLabel(*this, parit);
2996 InsetList::const_iterator iit = parit->insetList().begin();
2997 InsetList::const_iterator end = parit->insetList().end();
2998 for (; iit != end; ++iit) {
2999 parit.pos() = iit->pos;
3000 iit->inset->updateLabels(parit);