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"
28 #include "EmbeddedFiles.h"
30 #include "ErrorList.h"
33 #include "FuncRequest.h"
34 #include "InsetIterator.h"
35 #include "InsetList.h"
37 #include "LaTeXFeatures.h"
41 #include "LyXAction.h"
45 #include "output_docbook.h"
47 #include "output_latex.h"
48 #include "output_plaintext.h"
49 #include "paragraph_funcs.h"
50 #include "Paragraph.h"
51 #include "ParagraphParameters.h"
52 #include "ParIterator.h"
53 #include "PDFOptions.h"
57 #include "TexStream.h"
59 #include "TextClass.h"
60 #include "TocBackend.h"
62 #include "VCBackend.h"
66 #include "insets/InsetBibitem.h"
67 #include "insets/InsetBibtex.h"
68 #include "insets/InsetInclude.h"
69 #include "insets/InsetText.h"
71 #include "mathed/MacroTable.h"
72 #include "mathed/MathMacroTemplate.h"
73 #include "mathed/MathSupport.h"
75 #include "frontends/alert.h"
76 #include "frontends/Delegates.h"
77 #include "frontends/WorkAreaManager.h"
79 #include "graphics/Previews.h"
81 #include "support/convert.h"
82 #include "support/debug.h"
83 #include "support/ExceptionMessage.h"
84 #include "support/FileName.h"
85 #include "support/FileNameList.h"
86 #include "support/filetools.h"
87 #include "support/ForkedCalls.h"
88 #include "support/gettext.h"
89 #include "support/gzstream.h"
90 #include "support/lstrings.h"
91 #include "support/lyxalgo.h"
92 #include "support/os.h"
93 #include "support/Package.h"
94 #include "support/Path.h"
95 #include "support/textutils.h"
96 #include "support/types.h"
97 #include "support/FileZipListDir.h"
99 #include <boost/bind.hpp>
100 #include <boost/shared_ptr.hpp>
111 using namespace lyx::support;
115 namespace Alert = frontend::Alert;
116 namespace os = support::os;
120 int const LYX_FORMAT = 318;
122 typedef map<string, bool> DepClean;
123 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
130 Impl(Buffer & parent, FileName const & file, bool readonly);
143 mutable TexRow texrow;
144 Buffer const * parent_buffer;
146 /// need to regenerate .tex?
150 mutable bool lyx_clean;
152 /// is autosave needed?
153 mutable bool bak_clean;
155 /// is this a unnamed file (New...)?
161 /// name of the file the buffer is associated with.
164 /** Set to true only when the file is fully loaded.
165 * Used to prevent the premature generation of previews
166 * and by the citation inset.
168 bool file_fully_loaded;
171 mutable TocBackend toc_backend;
174 typedef pair<DocIterator, MacroData> ScopeMacro;
175 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
176 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
177 /// map from the macro name to the position map,
178 /// which maps the macro definition position to the scope and the MacroData.
179 NamePositionScopeMacroMap macros;
182 /// positions of child buffers in the buffer
183 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
184 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
185 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
186 /// position of children buffers in this buffer
187 BufferPositionMap children_positions;
188 /// map from children inclusion positions to their scope and their buffer
189 PositionScopeBufferMap position_to_children;
191 /// Container for all sort of Buffer dependant errors.
192 map<string, ErrorList> errorLists;
194 /// all embedded files of this buffer
195 EmbeddedFileList embedded_files;
197 /// timestamp and checksum used to test if the file has been externally
198 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
200 unsigned long checksum_;
203 frontend::WorkAreaManager * wa_;
208 /// A cache for the bibfiles (including bibfiles of loaded child
209 /// documents), needed for appropriate update of natbib labels.
210 mutable EmbeddedFileList bibfilesCache_;
212 mutable RefCache ref_cache_;
214 /// our Text that should be wrapped in an InsetText
218 /// Creates the per buffer temporary directory
219 static FileName createBufferTmpDir()
222 // We are in our own directory. Why bother to mangle name?
223 // In fact I wrote this code to circumvent a problematic behaviour
224 // (bug?) of EMX mkstemp().
225 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
226 convert<string>(count++));
228 if (!tmpfl.createDirectory(0777)) {
229 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
230 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
231 from_utf8(tmpfl.absFilename())));
237 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
238 : parent_buffer(0), lyx_clean(true), bak_clean(true), unnamed(false),
239 read_only(readonly_), filename(file), file_fully_loaded(false),
240 toc_backend(&parent), macro_lock(false),
241 embedded_files(), timestamp_(0), checksum_(0), wa_(0),
244 temppath = createBufferTmpDir();
245 lyxvc.setBuffer(&parent);
247 wa_ = new frontend::WorkAreaManager;
251 Buffer::Buffer(string const & file, bool readonly)
252 : d(new Impl(*this, FileName(file), readonly)), gui_(0)
254 LYXERR(Debug::INFO, "Buffer::Buffer()");
256 d->inset.setBuffer(*this);
257 d->inset.initParagraphs(*this);
258 d->inset.setAutoBreakRows(true);
259 d->inset.getText(0)->setMacrocontextPosition(par_iterator_begin());
265 LYXERR(Debug::INFO, "Buffer::~Buffer()");
266 // here the buffer should take care that it is
267 // saved properly, before it goes into the void.
269 // GuiView already destroyed
272 // clear references to children in macro tables
273 d->children_positions.clear();
274 d->position_to_children.clear();
276 if (!d->temppath.destroyDirectory()) {
277 Alert::warning(_("Could not remove temporary directory"),
278 bformat(_("Could not remove the temporary directory %1$s"),
279 from_utf8(d->temppath.absFilename())));
282 // Remove any previewed LaTeX snippets associated with this buffer.
283 graphics::Previews::get().removeLoader(*this);
289 void Buffer::changed() const
296 frontend::WorkAreaManager & Buffer::workAreaManager() const
298 BOOST_ASSERT(d->wa_);
303 Text & Buffer::text() const
305 return const_cast<Text &>(d->inset.text_);
309 Inset & Buffer::inset() const
311 return const_cast<InsetText &>(d->inset);
315 BufferParams & Buffer::params()
321 BufferParams const & Buffer::params() const
327 ParagraphList & Buffer::paragraphs()
329 return text().paragraphs();
333 ParagraphList const & Buffer::paragraphs() const
335 return text().paragraphs();
339 LyXVC & Buffer::lyxvc()
345 LyXVC const & Buffer::lyxvc() const
351 string const Buffer::temppath() const
353 return d->temppath.absFilename();
357 TexRow const & Buffer::texrow() const
363 TocBackend & Buffer::tocBackend() const
365 return d->toc_backend;
369 EmbeddedFileList & Buffer::embeddedFiles()
371 return d->embedded_files;
375 EmbeddedFileList const & Buffer::embeddedFiles() const
377 return d->embedded_files;
381 bool Buffer::embedded() const
383 return params().embedded;
387 Undo & Buffer::undo()
393 string Buffer::latexName(bool const no_path) const
395 FileName latex_name = makeLatexName(d->filename);
396 return no_path ? latex_name.onlyFileName()
397 : latex_name.absFilename();
401 string Buffer::logName(LogType * type) const
403 string const filename = latexName(false);
405 if (filename.empty()) {
411 string const path = temppath();
413 FileName const fname(addName(temppath(),
414 onlyFilename(changeExtension(filename,
416 FileName const bname(
417 addName(path, onlyFilename(
418 changeExtension(filename,
419 formats.extension("literate") + ".out"))));
421 // If no Latex log or Build log is newer, show Build log
423 if (bname.exists() &&
424 (!fname.exists() || fname.lastModified() < bname.lastModified())) {
425 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
428 return bname.absFilename();
430 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
433 return fname.absFilename();
437 void Buffer::setReadonly(bool const flag)
439 if (d->read_only != flag) {
446 void Buffer::setFileName(string const & newfile)
448 d->filename = makeAbsPath(newfile);
449 setReadonly(d->filename.isReadOnly());
454 int Buffer::readHeader(Lexer & lex)
456 int unknown_tokens = 0;
458 int begin_header_line = -1;
460 // Initialize parameters that may be/go lacking in header:
461 params().branchlist().clear();
462 params().preamble.erase();
463 params().options.erase();
464 params().float_placement.erase();
465 params().paperwidth.erase();
466 params().paperheight.erase();
467 params().leftmargin.erase();
468 params().rightmargin.erase();
469 params().topmargin.erase();
470 params().bottommargin.erase();
471 params().headheight.erase();
472 params().headsep.erase();
473 params().footskip.erase();
474 params().columnsep.erase();
475 params().listings_params.clear();
476 params().clearLayoutModules();
477 params().pdfoptions().clear();
479 for (int i = 0; i < 4; ++i) {
480 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
481 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
484 ErrorList & errorList = d->errorLists["Parse"];
488 string const token = lex.getString();
493 if (token == "\\end_header")
497 if (token == "\\begin_header") {
498 begin_header_line = line;
502 LYXERR(Debug::PARSER, "Handling document header token: `"
505 string unknown = params().readToken(lex, token, d->filename.onlyPath(),
507 if (!unknown.empty()) {
508 if (unknown[0] != '\\' && token == "\\textclass") {
509 Alert::warning(_("Unknown document class"),
510 bformat(_("Using the default document class, because the "
511 "class %1$s is unknown."), from_utf8(unknown)));
514 docstring const s = bformat(_("Unknown token: "
518 errorList.push_back(ErrorItem(_("Document header error"),
523 if (begin_header_line) {
524 docstring const s = _("\\begin_header is missing");
525 errorList.push_back(ErrorItem(_("Document header error"),
529 params().makeDocumentClass();
531 return unknown_tokens;
536 // changed to be public and have one parameter
537 // Returns false if "\end_document" is not read (Asger)
538 bool Buffer::readDocument(Lexer & lex)
540 ErrorList & errorList = d->errorLists["Parse"];
544 string const token = lex.getString();
545 if (token != "\\begin_document") {
546 docstring const s = _("\\begin_document is missing");
547 errorList.push_back(ErrorItem(_("Document header error"),
551 // we are reading in a brand new document
552 BOOST_ASSERT(paragraphs().empty());
556 if (params().outputChanges) {
557 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
558 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
559 LaTeXFeatures::isAvailable("xcolor");
561 if (!dvipost && !xcolorsoul) {
562 Alert::warning(_("Changes not shown in LaTeX output"),
563 _("Changes will not be highlighted in LaTeX output, "
564 "because neither dvipost nor xcolor/soul are installed.\n"
565 "Please install these packages or redefine "
566 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
567 } else if (!xcolorsoul) {
568 Alert::warning(_("Changes not shown in LaTeX output"),
569 _("Changes will not be highlighted in LaTeX output "
570 "when using pdflatex, because xcolor and soul are not installed.\n"
571 "Please install both packages or redefine "
572 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
577 bool const res = text().read(*this, lex, errorList, &(d->inset));
579 // Enable embeded files, which will set temp path and move
580 // inconsistent inzip files if needed.
582 embeddedFiles().validate(*this);
583 embeddedFiles().enable(params().embedded, *this, false);
584 } catch (ExceptionMessage const & message) {
585 Alert::error(message.title_, message.details_);
586 Alert::warning(_("Failed to read embedded files"),
587 _("Due to most likely a bug, LyX failed to locate all embedded "
588 "file. If you unzip the LyX file, you should be able to see and "
589 "open content.lyx which is your main text. You may also be able "
590 "to recover some embedded files. Please report this bug to the "
591 "lyx-devel mailing list."));
596 updateMacroInstances();
601 // needed to insert the selection
602 void Buffer::insertStringAsLines(ParagraphList & pars,
603 pit_type & pit, pos_type & pos,
604 Font const & fn, docstring const & str, bool autobreakrows)
608 // insert the string, don't insert doublespace
609 bool space_inserted = true;
610 for (docstring::const_iterator cit = str.begin();
611 cit != str.end(); ++cit) {
612 Paragraph & par = pars[pit];
614 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
615 breakParagraph(params(), pars, pit, pos,
616 par.layout().isEnvironment());
619 space_inserted = true;
623 // do not insert consecutive spaces if !free_spacing
624 } else if ((*cit == ' ' || *cit == '\t') &&
625 space_inserted && !par.isFreeSpacing()) {
627 } else if (*cit == '\t') {
628 if (!par.isFreeSpacing()) {
629 // tabs are like spaces here
630 par.insertChar(pos, ' ', font, params().trackChanges);
632 space_inserted = true;
634 const pos_type n = 8 - pos % 8;
635 for (pos_type i = 0; i < n; ++i) {
636 par.insertChar(pos, ' ', font, params().trackChanges);
639 space_inserted = true;
641 } else if (!isPrintable(*cit)) {
642 // Ignore unprintables
645 // just insert the character
646 par.insertChar(pos, *cit, font, params().trackChanges);
648 space_inserted = (*cit == ' ');
655 bool Buffer::readString(string const & s)
657 params().compressed = false;
659 // remove dummy empty par
660 paragraphs().clear();
664 FileName const name = FileName::tempName();
665 switch (readFile(lex, name, true)) {
669 // We need to call lyx2lyx, so write the input to a file
670 ofstream os(name.toFilesystemEncoding().c_str());
673 return readFile(name);
683 bool Buffer::readFile(FileName const & filename)
685 FileName fname(filename);
686 // Check if the file is compressed.
687 string format = filename.guessFormatFromContents();
688 if (format == "zip") {
689 // decompress to a temp directory
690 LYXERR(Debug::FILES, filename << " is in zip format. Unzip to " << temppath());
691 ::unzipToDir(filename.toFilesystemEncoding(), temppath());
693 FileName lyxfile(addName(temppath(), "content.lyx"));
694 // if both manifest.txt and file.lyx exist, this is am embedded file
695 if (lyxfile.exists()) {
696 // if in bundled format, save checksum of the compressed file, not content.lyx
697 saveCheckSum(filename);
698 params().embedded = true;
702 // The embedded lyx file can also be compressed, for backward compatibility
703 format = fname.guessFormatFromContents();
704 if (format == "gzip" || format == "zip" || format == "compress")
705 params().compressed = true;
707 // remove dummy empty par
708 paragraphs().clear();
711 if (readFile(lex, fname) != success)
718 bool Buffer::isFullyLoaded() const
720 return d->file_fully_loaded;
724 void Buffer::setFullyLoaded(bool value)
726 d->file_fully_loaded = value;
730 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
733 BOOST_ASSERT(!filename.empty());
736 Alert::error(_("Document could not be read"),
737 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
742 string const token = lex.getString();
745 Alert::error(_("Document could not be read"),
746 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
750 // the first token _must_ be...
751 if (token != "\\lyxformat") {
752 lyxerr << "Token: " << token << endl;
754 Alert::error(_("Document format failure"),
755 bformat(_("%1$s is not a LyX document."),
756 from_utf8(filename.absFilename())));
761 string tmp_format = lex.getString();
762 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
763 // if present remove ".," from string.
764 string::size_type dot = tmp_format.find_first_of(".,");
765 //lyxerr << " dot found at " << dot << endl;
766 if (dot != string::npos)
767 tmp_format.erase(dot, 1);
768 int const file_format = convert<int>(tmp_format);
769 //lyxerr << "format: " << file_format << endl;
771 // save timestamp and checksum of the original disk file, making sure
772 // to not overwrite them with those of the file created in the tempdir
773 // when it has to be converted to the current format.
775 // Save the timestamp and checksum of disk file. If filename is an
776 // emergency file, save the timestamp and checksum of the original lyx file
777 // because isExternallyModified will check for this file. (BUG4193)
778 string diskfile = filename.absFilename();
779 if (suffixIs(diskfile, ".emergency"))
780 diskfile = diskfile.substr(0, diskfile.size() - 10);
781 saveCheckSum(FileName(diskfile));
784 if (file_format != LYX_FORMAT) {
787 // lyx2lyx would fail
790 FileName const tmpfile = FileName::tempName();
791 if (tmpfile.empty()) {
792 Alert::error(_("Conversion failed"),
793 bformat(_("%1$s is from a different"
794 " version of LyX, but a temporary"
795 " file for converting it could"
797 from_utf8(filename.absFilename())));
800 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
801 if (lyx2lyx.empty()) {
802 Alert::error(_("Conversion script not found"),
803 bformat(_("%1$s is from a different"
804 " version of LyX, but the"
805 " conversion script lyx2lyx"
806 " could not be found."),
807 from_utf8(filename.absFilename())));
810 ostringstream command;
811 command << os::python()
812 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
813 << " -t " << convert<string>(LYX_FORMAT)
814 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
815 << ' ' << quoteName(filename.toFilesystemEncoding());
816 string const command_str = command.str();
818 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
820 cmd_ret const ret = runCommand(command_str);
821 if (ret.first != 0) {
822 Alert::error(_("Conversion script failed"),
823 bformat(_("%1$s is from a different version"
824 " of LyX, but the lyx2lyx script"
825 " failed to convert it."),
826 from_utf8(filename.absFilename())));
829 bool const ret = readFile(tmpfile);
830 // Do stuff with tmpfile name and buffer name here.
831 return ret ? success : failure;
836 if (readDocument(lex)) {
837 Alert::error(_("Document format failure"),
838 bformat(_("%1$s ended unexpectedly, which means"
839 " that it is probably corrupted."),
840 from_utf8(filename.absFilename())));
843 d->file_fully_loaded = true;
848 // Should probably be moved to somewhere else: BufferView? LyXView?
849 bool Buffer::save() const
851 // We don't need autosaves in the immediate future. (Asger)
852 resetAutosaveTimers();
854 string const encodedFilename = d->filename.toFilesystemEncoding();
857 bool madeBackup = false;
859 // make a backup if the file already exists
860 if (lyxrc.make_backup && fileName().exists()) {
861 backupName = FileName(absFileName() + '~');
862 if (!lyxrc.backupdir_path.empty()) {
863 string const mangledName =
864 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
865 backupName = FileName(addName(lyxrc.backupdir_path,
868 if (fileName().copyTo(backupName)) {
871 Alert::error(_("Backup failure"),
872 bformat(_("Cannot create backup file %1$s.\n"
873 "Please check whether the directory exists and is writeable."),
874 from_utf8(backupName.absFilename())));
875 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
879 // ask if the disk file has been externally modified (use checksum method)
880 if (fileName().exists() && isExternallyModified(checksum_method)) {
881 docstring const file = makeDisplayPath(absFileName(), 20);
882 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
883 "you want to overwrite this file?"), file);
884 int const ret = Alert::prompt(_("Overwrite modified file?"),
885 text, 1, 1, _("&Overwrite"), _("&Cancel"));
890 if (writeFile(d->filename)) {
894 // Saving failed, so backup is not backup
896 backupName.moveTo(d->filename);
902 bool Buffer::writeFile(FileName const & fname) const
904 if (d->read_only && fname == d->filename)
910 if (params().embedded)
911 // first write the .lyx file to the temporary directory
912 content = FileName(addName(temppath(), "content.lyx"));
916 docstring const str = bformat(_("Saving document %1$s..."),
917 makeDisplayPath(content.absFilename()));
920 if (params().compressed) {
921 gz::ogzstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
922 retval = ofs && write(ofs);
924 ofstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
925 retval = ofs && write(ofs);
929 message(str + _(" could not write file!."));
933 removeAutosaveFile(d->filename.absFilename());
935 if (params().embedded) {
936 message(str + _(" writing embedded files!."));
937 // if embedding is enabled, write file.lyx and all the embedded files
938 // to the zip file fname.
939 if (!d->embedded_files.writeFile(fname, *this)) {
940 message(str + _(" could not write embedded files!."));
944 saveCheckSum(d->filename);
945 message(str + _(" done."));
951 bool Buffer::write(ostream & ofs) const
954 // Use the standard "C" locale for file output.
955 ofs.imbue(locale::classic());
958 // The top of the file should not be written by params().
960 // write out a comment in the top of the file
961 ofs << "#LyX " << lyx_version
962 << " created this file. For more info see http://www.lyx.org/\n"
963 << "\\lyxformat " << LYX_FORMAT << "\n"
964 << "\\begin_document\n";
966 /// For each author, set 'used' to true if there is a change
967 /// by this author in the document; otherwise set it to 'false'.
968 AuthorList::Authors::const_iterator a_it = params().authors().begin();
969 AuthorList::Authors::const_iterator a_end = params().authors().end();
970 for (; a_it != a_end; ++a_it)
971 a_it->second.setUsed(false);
973 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
974 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
975 for ( ; it != end; ++it)
976 it->checkAuthors(params().authors());
978 // now write out the buffer parameters.
979 ofs << "\\begin_header\n";
980 params().writeFile(ofs);
981 ofs << "\\end_header\n";
984 ofs << "\n\\begin_body\n";
985 text().write(*this, ofs);
986 ofs << "\n\\end_body\n";
988 // Write marker that shows file is complete
989 ofs << "\\end_document" << endl;
991 // Shouldn't really be needed....
994 // how to check if close went ok?
995 // Following is an attempt... (BE 20001011)
997 // good() returns false if any error occured, including some
999 // bad() returns true if something bad happened in the buffer,
1000 // which should include file system full errors.
1005 lyxerr << "File was not closed properly." << endl;
1012 bool Buffer::makeLaTeXFile(FileName const & fname,
1013 string const & original_path,
1014 OutputParams const & runparams,
1015 bool output_preamble, bool output_body) const
1017 string const encoding = runparams.encoding->iconvName();
1018 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1021 try { ofs.reset(encoding); }
1022 catch (iconv_codecvt_facet_exception & e) {
1023 lyxerr << "Caught iconv exception: " << e.what() << endl;
1024 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1025 "verify that the support software for your encoding (%1$s) is "
1026 "properly installed"), from_ascii(encoding)));
1029 if (!openFileWrite(ofs, fname))
1032 //TexStream ts(ofs.rdbuf(), &texrow());
1033 ErrorList & errorList = d->errorLists["Export"];
1035 bool failed_export = false;
1038 writeLaTeXSource(ofs, original_path,
1039 runparams, output_preamble, output_body);
1041 catch (EncodingException & e) {
1042 odocstringstream ods;
1043 ods.put(e.failed_char);
1045 oss << "0x" << hex << e.failed_char << dec;
1046 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1047 " (code point %2$s)"),
1048 ods.str(), from_utf8(oss.str()));
1049 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1050 "representable in the chosen encoding.\n"
1051 "Changing the document encoding to utf8 could help."),
1052 e.par_id, e.pos, e.pos + 1));
1053 failed_export = true;
1055 catch (iconv_codecvt_facet_exception & e) {
1056 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1057 _(e.what()), -1, 0, 0));
1058 failed_export = true;
1060 catch (exception const & e) {
1061 errorList.push_back(ErrorItem(_("conversion failed"),
1062 _(e.what()), -1, 0, 0));
1063 failed_export = true;
1066 lyxerr << "Caught some really weird exception..." << endl;
1067 LyX::cref().exit(1);
1072 failed_export = true;
1073 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1077 return !failed_export;
1081 void Buffer::writeLaTeXSource(odocstream & os,
1082 string const & original_path,
1083 OutputParams const & runparams_in,
1084 bool const output_preamble, bool const output_body) const
1086 // The child documents, if any, shall be already loaded at this point.
1088 OutputParams runparams = runparams_in;
1090 // validate the buffer.
1091 LYXERR(Debug::LATEX, " Validating buffer...");
1092 LaTeXFeatures features(*this, params(), runparams);
1094 LYXERR(Debug::LATEX, " Buffer validation done.");
1096 // The starting paragraph of the coming rows is the
1097 // first paragraph of the document. (Asger)
1098 if (output_preamble && runparams.nice) {
1099 os << "%% LyX " << lyx_version << " created this file. "
1100 "For more info, see http://www.lyx.org/.\n"
1101 "%% Do not edit unless you really know what "
1103 d->texrow.newline();
1104 d->texrow.newline();
1106 LYXERR(Debug::INFO, "lyx document header finished");
1107 // There are a few differences between nice LaTeX and usual files:
1108 // usual is \batchmode and has a
1109 // special input@path to allow the including of figures
1110 // with either \input or \includegraphics (what figinsets do).
1111 // input@path is set when the actual parameter
1112 // original_path is set. This is done for usual tex-file, but not
1113 // for nice-latex-file. (Matthias 250696)
1114 // Note that input@path is only needed for something the user does
1115 // in the preamble, included .tex files or ERT, files included by
1116 // LyX work without it.
1117 if (output_preamble) {
1118 if (!runparams.nice) {
1119 // code for usual, NOT nice-latex-file
1120 os << "\\batchmode\n"; // changed
1121 // from \nonstopmode
1122 d->texrow.newline();
1124 if (!original_path.empty()) {
1126 // We don't know the encoding of inputpath
1127 docstring const inputpath = from_utf8(latex_path(original_path));
1128 os << "\\makeatletter\n"
1129 << "\\def\\input@path{{"
1130 << inputpath << "/}}\n"
1131 << "\\makeatother\n";
1132 d->texrow.newline();
1133 d->texrow.newline();
1134 d->texrow.newline();
1137 // Write the preamble
1138 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1144 os << "\\begin{document}\n";
1145 d->texrow.newline();
1146 } // output_preamble
1148 d->texrow.start(paragraphs().begin()->id(), 0);
1150 LYXERR(Debug::INFO, "preamble finished, now the body.");
1152 // Don't move this behind the parent_buffer=0 code below,
1153 // because then the macros will not get the right "redefinition"
1154 // flag as they don't see the parent macros which are output before.
1157 // fold macros if possible, still with parent buffer as the
1158 // macros will be put in the prefix anyway.
1159 updateMacroInstances();
1161 // if we are doing a real file with body, even if this is the
1162 // child of some other buffer, let's cut the link here.
1163 // This happens for example if only a child document is printed.
1164 Buffer const * save_parent = 0;
1165 if (output_preamble) {
1166 // output the macros visible for this buffer
1167 writeParentMacros(os);
1169 save_parent = d->parent_buffer;
1170 d->parent_buffer = 0;
1174 latexParagraphs(*this, text(), os, d->texrow, runparams);
1176 // Restore the parenthood if needed
1177 if (output_preamble) {
1178 d->parent_buffer = save_parent;
1180 // restore macros with correct parent buffer (especially
1181 // important for the redefinition flag which depends on the
1186 // add this just in case after all the paragraphs
1188 d->texrow.newline();
1190 if (output_preamble) {
1191 os << "\\end{document}\n";
1192 d->texrow.newline();
1193 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1195 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1197 runparams_in.encoding = runparams.encoding;
1199 // Just to be sure. (Asger)
1200 d->texrow.newline();
1202 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1203 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1207 bool Buffer::isLatex() const
1209 return params().documentClass().outputType() == LATEX;
1213 bool Buffer::isLiterate() const
1215 return params().documentClass().outputType() == LITERATE;
1219 bool Buffer::isDocBook() const
1221 return params().documentClass().outputType() == DOCBOOK;
1225 void Buffer::makeDocBookFile(FileName const & fname,
1226 OutputParams const & runparams,
1227 bool const body_only) const
1229 LYXERR(Debug::LATEX, "makeDocBookFile...");
1232 if (!openFileWrite(ofs, fname))
1235 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1239 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1243 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1244 OutputParams const & runparams,
1245 bool const only_body) const
1247 LaTeXFeatures features(*this, params(), runparams);
1252 DocumentClass const & tclass = params().documentClass();
1253 string const top_element = tclass.latexname();
1256 if (runparams.flavor == OutputParams::XML)
1257 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1260 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1263 if (! tclass.class_header().empty())
1264 os << from_ascii(tclass.class_header());
1265 else if (runparams.flavor == OutputParams::XML)
1266 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1267 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1269 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1271 docstring preamble = from_utf8(params().preamble);
1272 if (runparams.flavor != OutputParams::XML ) {
1273 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1274 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1275 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1276 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1279 string const name = runparams.nice
1280 ? changeExtension(absFileName(), ".sgml") : fname;
1281 preamble += features.getIncludedFiles(name);
1282 preamble += features.getLyXSGMLEntities();
1284 if (!preamble.empty()) {
1285 os << "\n [ " << preamble << " ]";
1290 string top = top_element;
1292 if (runparams.flavor == OutputParams::XML)
1293 top += params().language->code();
1295 top += params().language->code().substr(0,2);
1298 if (!params().options.empty()) {
1300 top += params().options;
1303 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1304 << " file was created by LyX " << lyx_version
1305 << "\n See http://www.lyx.org/ for more information -->\n";
1307 params().documentClass().counters().reset();
1311 sgml::openTag(os, top);
1313 docbookParagraphs(paragraphs(), *this, os, runparams);
1314 sgml::closeTag(os, top_element);
1318 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1319 // Other flags: -wall -v0 -x
1320 int Buffer::runChktex()
1324 // get LaTeX-Filename
1325 FileName const path(temppath());
1326 string const name = addName(path.absFilename(), latexName());
1327 string const org_path = filePath();
1329 PathChanger p(path); // path to LaTeX file
1330 message(_("Running chktex..."));
1332 // Generate the LaTeX file if neccessary
1333 OutputParams runparams(¶ms().encoding());
1334 runparams.flavor = OutputParams::LATEX;
1335 runparams.nice = false;
1336 makeLaTeXFile(FileName(name), org_path, runparams);
1339 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1340 int const res = chktex.run(terr); // run chktex
1343 Alert::error(_("chktex failure"),
1344 _("Could not run chktex successfully."));
1345 } else if (res > 0) {
1346 ErrorList & errlist = d->errorLists["ChkTeX"];
1348 bufferErrors(terr, errlist);
1359 void Buffer::validate(LaTeXFeatures & features) const
1361 params().validate(features);
1365 for_each(paragraphs().begin(), paragraphs().end(),
1366 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1368 if (lyxerr.debugging(Debug::LATEX)) {
1369 features.showStruct();
1374 void Buffer::getLabelList(vector<docstring> & list) const
1376 // If this is a child document, use the parent's list instead.
1377 if (d->parent_buffer) {
1378 d->parent_buffer->getLabelList(list);
1383 Toc & toc = d->toc_backend.toc("label");
1384 TocIterator toc_it = toc.begin();
1385 TocIterator end = toc.end();
1386 for (; toc_it != end; ++toc_it) {
1387 if (toc_it->depth() == 0)
1388 list.push_back(toc_it->str());
1393 void Buffer::updateBibfilesCache() const
1395 // If this is a child document, use the parent's cache instead.
1396 if (d->parent_buffer) {
1397 d->parent_buffer->updateBibfilesCache();
1401 d->bibfilesCache_.clear();
1402 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1403 if (it->lyxCode() == BIBTEX_CODE) {
1404 InsetBibtex const & inset =
1405 static_cast<InsetBibtex const &>(*it);
1406 EmbeddedFileList const bibfiles = inset.embeddedFiles();
1407 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1410 } else if (it->lyxCode() == INCLUDE_CODE) {
1411 InsetInclude & inset =
1412 static_cast<InsetInclude &>(*it);
1413 inset.updateBibfilesCache();
1414 EmbeddedFileList const & bibfiles =
1415 inset.getBibfilesCache(*this);
1416 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1424 EmbeddedFileList const & Buffer::getBibfilesCache() const
1426 // If this is a child document, use the parent's cache instead.
1427 if (d->parent_buffer)
1428 return d->parent_buffer->getBibfilesCache();
1430 // We update the cache when first used instead of at loading time.
1431 if (d->bibfilesCache_.empty())
1432 const_cast<Buffer *>(this)->updateBibfilesCache();
1434 return d->bibfilesCache_;
1438 bool Buffer::isDepClean(string const & name) const
1440 DepClean::const_iterator const it = d->dep_clean.find(name);
1441 if (it == d->dep_clean.end())
1447 void Buffer::markDepClean(string const & name)
1449 d->dep_clean[name] = true;
1453 bool Buffer::dispatch(string const & command, bool * result)
1455 return dispatch(lyxaction.lookupFunc(command), result);
1459 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1461 bool dispatched = true;
1463 switch (func.action) {
1464 case LFUN_BUFFER_EXPORT: {
1465 bool const tmp = doExport(to_utf8(func.argument()), false);
1478 void Buffer::changeLanguage(Language const * from, Language const * to)
1483 for_each(par_iterator_begin(),
1485 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1489 bool Buffer::isMultiLingual() const
1491 ParConstIterator end = par_iterator_end();
1492 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1493 if (it->isMultiLingual(params()))
1500 DocIterator Buffer::getParFromID(int const id) const
1503 // John says this is called with id == -1 from undo
1504 lyxerr << "getParFromID(), id: " << id << endl;
1505 return doc_iterator_end(inset());
1508 for (DocIterator it = doc_iterator_begin(inset()); !it.atEnd(); it.forwardPar())
1509 if (it.paragraph().id() == id)
1512 return doc_iterator_end(inset());
1516 bool Buffer::hasParWithID(int const id) const
1518 return !getParFromID(id).atEnd();
1522 ParIterator Buffer::par_iterator_begin()
1524 return ParIterator(doc_iterator_begin(inset()));
1528 ParIterator Buffer::par_iterator_end()
1530 return ParIterator(doc_iterator_end(inset()));
1534 ParConstIterator Buffer::par_iterator_begin() const
1536 return lyx::par_const_iterator_begin(inset());
1540 ParConstIterator Buffer::par_iterator_end() const
1542 return lyx::par_const_iterator_end(inset());
1546 Language const * Buffer::language() const
1548 return params().language;
1552 docstring const Buffer::B_(string const & l10n) const
1554 return params().B_(l10n);
1558 bool Buffer::isClean() const
1560 return d->lyx_clean;
1564 bool Buffer::isBakClean() const
1566 return d->bak_clean;
1570 bool Buffer::isExternallyModified(CheckMethod method) const
1572 BOOST_ASSERT(d->filename.exists());
1573 // if method == timestamp, check timestamp before checksum
1574 return (method == checksum_method
1575 || d->timestamp_ != d->filename.lastModified())
1576 && d->checksum_ != d->filename.checksum();
1580 void Buffer::saveCheckSum(FileName const & file) const
1582 if (file.exists()) {
1583 d->timestamp_ = file.lastModified();
1584 d->checksum_ = file.checksum();
1586 // in the case of save to a new file.
1593 void Buffer::markClean() const
1595 if (!d->lyx_clean) {
1596 d->lyx_clean = true;
1599 // if the .lyx file has been saved, we don't need an
1601 d->bak_clean = true;
1605 void Buffer::markBakClean() const
1607 d->bak_clean = true;
1611 void Buffer::setUnnamed(bool flag)
1617 bool Buffer::isUnnamed() const
1623 // FIXME: this function should be moved to buffer_pimpl.C
1624 void Buffer::markDirty()
1627 d->lyx_clean = false;
1630 d->bak_clean = false;
1632 DepClean::iterator it = d->dep_clean.begin();
1633 DepClean::const_iterator const end = d->dep_clean.end();
1635 for (; it != end; ++it)
1640 FileName Buffer::fileName() const
1646 string Buffer::absFileName() const
1648 return d->filename.absFilename();
1652 string Buffer::filePath() const
1654 return d->filename.onlyPath().absFilename() + "/";
1658 bool Buffer::isReadonly() const
1660 return d->read_only;
1664 void Buffer::setParent(Buffer const * buffer)
1666 // Avoids recursive include.
1667 d->parent_buffer = buffer == this ? 0 : buffer;
1672 Buffer const * Buffer::parent()
1674 return d->parent_buffer;
1678 Buffer const * Buffer::masterBuffer() const
1680 if (!d->parent_buffer)
1683 return d->parent_buffer->masterBuffer();
1687 template<typename M>
1688 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
1693 typename M::iterator it = m.lower_bound(x);
1694 if (it == m.begin())
1702 MacroData const * Buffer::getBufferMacro(docstring const & name,
1703 DocIterator const & pos) const
1705 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
1707 // if paragraphs have no macro context set, pos will be empty
1711 // we haven't found anything yet
1712 DocIterator bestPos = par_iterator_begin();
1713 MacroData const * bestData = 0;
1715 // find macro definitions for name
1716 Impl::NamePositionScopeMacroMap::iterator nameIt
1717 = d->macros.find(name);
1718 if (nameIt != d->macros.end()) {
1719 // find last definition in front of pos or at pos itself
1720 Impl::PositionScopeMacroMap::const_iterator it
1721 = greatest_below(nameIt->second, pos);
1722 if (it != nameIt->second.end()) {
1724 // scope ends behind pos?
1725 if (pos < it->second.first) {
1726 // Looks good, remember this. If there
1727 // is no external macro behind this,
1728 // we found the right one already.
1729 bestPos = it->first;
1730 bestData = &it->second.second;
1734 // try previous macro if there is one
1735 if (it == nameIt->second.begin())
1742 // find macros in included files
1743 Impl::PositionScopeBufferMap::const_iterator it
1744 = greatest_below(d->position_to_children, pos);
1745 if (it == d->position_to_children.end())
1746 // no children before
1750 // do we know something better (i.e. later) already?
1751 if (it->first < bestPos )
1754 // scope ends behind pos?
1755 if (pos < it->second.first) {
1756 // look for macro in external file
1757 d->macro_lock = true;
1758 MacroData const * data
1759 = it->second.second->getMacro(name, false);
1760 d->macro_lock = false;
1762 bestPos = it->first;
1768 // try previous file if there is one
1769 if (it == d->position_to_children.begin())
1774 // return the best macro we have found
1779 MacroData const * Buffer::getMacro(docstring const & name,
1780 DocIterator const & pos, bool global) const
1785 // query buffer macros
1786 MacroData const * data = getBufferMacro(name, pos);
1790 // If there is a master buffer, query that
1791 if (d->parent_buffer) {
1792 d->macro_lock = true;
1793 MacroData const * macro = d->parent_buffer->getMacro(
1794 name, *this, false);
1795 d->macro_lock = false;
1801 data = MacroTable::globalMacros().get(name);
1810 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
1812 // set scope end behind the last paragraph
1813 DocIterator scope = par_iterator_begin();
1814 scope.pit() = scope.lastpit() + 1;
1816 return getMacro(name, scope, global);
1820 MacroData const * Buffer::getMacro(docstring const & name,
1821 Buffer const & child, bool global) const
1823 // look where the child buffer is included first
1824 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
1825 if (it == d->children_positions.end())
1828 // check for macros at the inclusion position
1829 return getMacro(name, it->second, global);
1833 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
1835 pit_type lastpit = it.lastpit();
1837 // look for macros in each paragraph
1838 while (it.pit() <= lastpit) {
1839 Paragraph & par = it.paragraph();
1841 // iterate over the insets of the current paragraph
1842 InsetList const & insets = par.insetList();
1843 InsetList::const_iterator iit = insets.begin();
1844 InsetList::const_iterator end = insets.end();
1845 for (; iit != end; ++iit) {
1846 it.pos() = iit->pos;
1848 // is it a nested text inset?
1849 if (iit->inset->asInsetText()) {
1850 // Inset needs its own scope?
1851 InsetText const * itext
1852 = iit->inset->asInsetText();
1853 bool newScope = itext->isMacroScope();
1855 // scope which ends just behind the inset
1856 DocIterator insetScope = it;
1859 // collect macros in inset
1860 it.push_back(CursorSlice(*iit->inset));
1861 updateMacros(it, newScope ? insetScope : scope);
1866 // is it an external file?
1867 if (iit->inset->lyxCode() == INCLUDE_CODE) {
1868 // get buffer of external file
1869 InsetCommand const & inset
1870 = static_cast<InsetCommand const &>(*iit->inset);
1871 InsetCommandParams const & ip = inset.params();
1872 d->macro_lock = true;
1873 Buffer * child = loadIfNeeded(*this, ip);
1874 d->macro_lock = false;
1878 // register its position, but only when it is
1879 // included first in the buffer
1880 if (d->children_positions.find(child)
1881 == d->children_positions.end())
1882 d->children_positions[child] = it;
1884 // register child with its scope
1885 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
1889 if (iit->inset->lyxCode() != MATHMACRO_CODE)
1893 MathMacroTemplate & macroTemplate
1894 = static_cast<MathMacroTemplate &>(*iit->inset);
1895 MacroContext mc(*this, it);
1896 macroTemplate.updateToContext(mc);
1899 bool valid = macroTemplate.validMacro();
1900 // FIXME: Should be fixNameAndCheckIfValid() in fact,
1901 // then the BufferView's cursor will be invalid in
1902 // some cases which leads to crashes.
1907 d->macros[macroTemplate.name()][it] =
1908 Impl::ScopeMacro(scope, MacroData(*this, it));
1918 void Buffer::updateMacros() const
1923 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
1925 // start with empty table
1927 d->children_positions.clear();
1928 d->position_to_children.clear();
1930 // Iterate over buffer, starting with first paragraph
1931 // The scope must be bigger than any lookup DocIterator
1932 // later. For the global lookup, lastpit+1 is used, hence
1933 // we use lastpit+2 here.
1934 DocIterator it = par_iterator_begin();
1935 DocIterator outerScope = it;
1936 outerScope.pit() = outerScope.lastpit() + 2;
1937 updateMacros(it, outerScope);
1941 void Buffer::updateMacroInstances() const
1943 LYXERR(Debug::MACROS, "updateMacroInstances for "
1944 << d->filename.onlyFileName());
1945 DocIterator it = doc_iterator_begin(inset());
1946 DocIterator end = doc_iterator_end(inset());
1947 for (; it != end; it.forwardPos()) {
1948 // look for MathData cells in InsetMathNest insets
1949 Inset * inset = it.nextInset();
1953 InsetMath * minset = inset->asInsetMath();
1957 // update macro in all cells of the InsetMathNest
1958 DocIterator::idx_type n = minset->nargs();
1959 MacroContext mc = MacroContext(*this, it);
1960 for (DocIterator::idx_type i = 0; i < n; ++i) {
1961 MathData & data = minset->cell(i);
1962 data.updateMacros(0, mc);
1968 void Buffer::listMacroNames(MacroNameSet & macros) const
1973 d->macro_lock = true;
1975 // loop over macro names
1976 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
1977 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
1978 for (; nameIt != nameEnd; ++nameIt)
1979 macros.insert(nameIt->first);
1981 // loop over children
1982 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
1983 Impl::BufferPositionMap::iterator end = d->children_positions.end();
1984 for (; it != end; ++it)
1985 it->first->listMacroNames(macros);
1988 if (d->parent_buffer)
1989 d->parent_buffer->listMacroNames(macros);
1991 d->macro_lock = false;
1995 void Buffer::writeParentMacros(odocstream & os) const
1997 if (!d->parent_buffer)
2000 // collect macro names
2002 d->parent_buffer->listMacroNames(names);
2004 // resolve and output them
2005 MacroNameSet::iterator it = names.begin();
2006 MacroNameSet::iterator end = names.end();
2007 for (; it != end; ++it) {
2009 MacroData const * data =
2010 d->parent_buffer->getMacro(*it, *this, false);
2012 data->write(os, true);
2017 Buffer::References & Buffer::references(docstring const & label)
2019 if (d->parent_buffer)
2020 return const_cast<Buffer *>(masterBuffer())->references(label);
2022 RefCache::iterator it = d->ref_cache_.find(label);
2023 if (it != d->ref_cache_.end())
2024 return it->second.second;
2026 static InsetLabel const * dummy_il = 0;
2027 static References const dummy_refs;
2028 it = d->ref_cache_.insert(
2029 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2030 return it->second.second;
2034 Buffer::References const & Buffer::references(docstring const & label) const
2036 return const_cast<Buffer *>(this)->references(label);
2040 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2042 masterBuffer()->d->ref_cache_[label].first = il;
2046 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2048 return masterBuffer()->d->ref_cache_[label].first;
2052 void Buffer::clearReferenceCache() const
2054 if (!d->parent_buffer)
2055 d->ref_cache_.clear();
2059 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2062 //FIXME: This does not work for child documents yet.
2063 BOOST_ASSERT(code == CITE_CODE);
2064 // Check if the label 'from' appears more than once
2065 vector<docstring> labels;
2068 keys.fillWithBibKeys(this);
2069 BiblioInfo::const_iterator bit = keys.begin();
2070 BiblioInfo::const_iterator bend = keys.end();
2072 for (; bit != bend; ++bit)
2074 labels.push_back(bit->first);
2077 if (count(labels.begin(), labels.end(), from) > 1)
2080 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2081 if (it->lyxCode() == code) {
2082 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2083 docstring const oldValue = inset.getParam(paramName);
2084 if (oldValue == from)
2085 inset.setParam(paramName, to);
2091 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2092 pit_type par_end, bool full_source)
2094 OutputParams runparams(¶ms().encoding());
2095 runparams.nice = true;
2096 runparams.flavor = OutputParams::LATEX;
2097 runparams.linelen = lyxrc.plaintext_linelen;
2098 // No side effect of file copying and image conversion
2099 runparams.dryrun = true;
2103 os << "% " << _("Preview source code") << "\n\n";
2104 d->texrow.newline();
2105 d->texrow.newline();
2107 writeLaTeXSource(os, filePath(), runparams, true, true);
2109 writeDocBookSource(os, absFileName(), runparams, false);
2111 runparams.par_begin = par_begin;
2112 runparams.par_end = par_end;
2113 if (par_begin + 1 == par_end) {
2115 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2119 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2120 convert<docstring>(par_begin),
2121 convert<docstring>(par_end - 1))
2124 d->texrow.newline();
2125 d->texrow.newline();
2126 // output paragraphs
2128 latexParagraphs(*this, text(), os, d->texrow, runparams);
2131 docbookParagraphs(paragraphs(), *this, os, runparams);
2136 ErrorList & Buffer::errorList(string const & type) const
2138 static ErrorList emptyErrorList;
2139 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2140 if (I == d->errorLists.end())
2141 return emptyErrorList;
2147 void Buffer::structureChanged() const
2150 gui_->structureChanged();
2154 void Buffer::errors(string const & err) const
2161 void Buffer::message(docstring const & msg) const
2168 void Buffer::setBusy(bool on) const
2175 void Buffer::setReadOnly(bool on) const
2178 d->wa_->setReadOnly(on);
2182 void Buffer::updateTitles() const
2185 d->wa_->updateTitles();
2189 void Buffer::resetAutosaveTimers() const
2192 gui_->resetAutosaveTimers();
2196 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2205 class AutoSaveBuffer : public ForkedProcess {
2208 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2209 : buffer_(buffer), fname_(fname) {}
2211 virtual boost::shared_ptr<ForkedProcess> clone() const
2213 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2218 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2219 from_utf8(fname_.absFilename())));
2220 return run(DontWait);
2224 virtual int generateChild();
2226 Buffer const & buffer_;
2231 int AutoSaveBuffer::generateChild()
2233 // tmp_ret will be located (usually) in /tmp
2234 // will that be a problem?
2235 // Note that this calls ForkedCalls::fork(), so it's
2236 // ok cross-platform.
2237 pid_t const pid = fork();
2238 // If you want to debug the autosave
2239 // you should set pid to -1, and comment out the fork.
2240 if (pid != 0 && pid != -1)
2243 // pid = -1 signifies that lyx was unable
2244 // to fork. But we will do the save
2246 bool failed = false;
2247 FileName const tmp_ret = FileName::tempName("lyxauto");
2248 if (!tmp_ret.empty()) {
2249 buffer_.writeFile(tmp_ret);
2250 // assume successful write of tmp_ret
2251 if (!tmp_ret.moveTo(fname_))
2257 // failed to write/rename tmp_ret so try writing direct
2258 if (!buffer_.writeFile(fname_)) {
2259 // It is dangerous to do this in the child,
2260 // but safe in the parent, so...
2261 if (pid == -1) // emit message signal.
2262 buffer_.message(_("Autosave failed!"));
2266 if (pid == 0) // we are the child so...
2275 // Perfect target for a thread...
2276 void Buffer::autoSave() const
2278 if (isBakClean() || isReadonly()) {
2279 // We don't save now, but we'll try again later
2280 resetAutosaveTimers();
2284 // emit message signal.
2285 message(_("Autosaving current document..."));
2287 // create autosave filename
2288 string fname = filePath();
2290 fname += d->filename.onlyFileName();
2293 AutoSaveBuffer autosave(*this, FileName(fname));
2297 resetAutosaveTimers();
2301 string Buffer::bufferFormat() const
2311 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2312 string & result_file) const
2314 string backend_format;
2315 OutputParams runparams(¶ms().encoding());
2316 runparams.flavor = OutputParams::LATEX;
2317 runparams.linelen = lyxrc.plaintext_linelen;
2318 vector<string> backs = backends();
2319 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2320 // Get shortest path to format
2321 Graph::EdgePath path;
2322 for (vector<string>::const_iterator it = backs.begin();
2323 it != backs.end(); ++it) {
2324 Graph::EdgePath p = theConverters().getPath(*it, format);
2325 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2326 backend_format = *it;
2331 runparams.flavor = theConverters().getFlavor(path);
2333 Alert::error(_("Couldn't export file"),
2334 bformat(_("No information for exporting the format %1$s."),
2335 formats.prettyName(format)));
2339 backend_format = format;
2340 // FIXME: Don't hardcode format names here, but use a flag
2341 if (backend_format == "pdflatex")
2342 runparams.flavor = OutputParams::PDFLATEX;
2345 string filename = latexName(false);
2346 filename = addName(temppath(), filename);
2347 filename = changeExtension(filename,
2348 formats.extension(backend_format));
2351 updateMacroInstances();
2353 // Plain text backend
2354 if (backend_format == "text")
2355 writePlaintextFile(*this, FileName(filename), runparams);
2357 else if (backend_format == "lyx")
2358 writeFile(FileName(filename));
2360 else if (isDocBook()) {
2361 runparams.nice = !put_in_tempdir;
2362 makeDocBookFile(FileName(filename), runparams);
2365 else if (backend_format == format) {
2366 runparams.nice = true;
2367 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2369 } else if (!lyxrc.tex_allows_spaces
2370 && contains(filePath(), ' ')) {
2371 Alert::error(_("File name error"),
2372 _("The directory path to the document cannot contain spaces."));
2375 runparams.nice = false;
2376 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2380 string const error_type = (format == "program")
2381 ? "Build" : bufferFormat();
2382 string const ext = formats.extension(format);
2383 FileName const tmp_result_file(changeExtension(filename, ext));
2384 bool const success = theConverters().convert(this, FileName(filename),
2385 tmp_result_file, FileName(absFileName()), backend_format, format,
2386 errorList(error_type));
2387 // Emit the signal to show the error list.
2388 if (format != backend_format)
2393 if (put_in_tempdir) {
2394 result_file = tmp_result_file.absFilename();
2398 result_file = changeExtension(absFileName(), ext);
2399 // We need to copy referenced files (e. g. included graphics
2400 // if format == "dvi") to the result dir.
2401 vector<ExportedFile> const files =
2402 runparams.exportdata->externalFiles(format);
2403 string const dest = onlyPath(result_file);
2404 CopyStatus status = SUCCESS;
2405 for (vector<ExportedFile>::const_iterator it = files.begin();
2406 it != files.end() && status != CANCEL; ++it) {
2407 string const fmt = formats.getFormatFromFile(it->sourceName);
2408 status = copyFile(fmt, it->sourceName,
2409 makeAbsPath(it->exportName, dest),
2410 it->exportName, status == FORCE);
2412 if (status == CANCEL) {
2413 message(_("Document export cancelled."));
2414 } else if (tmp_result_file.exists()) {
2415 // Finally copy the main file
2416 status = copyFile(format, tmp_result_file,
2417 FileName(result_file), result_file,
2419 message(bformat(_("Document exported as %1$s "
2421 formats.prettyName(format),
2422 makeDisplayPath(result_file)));
2424 // This must be a dummy converter like fax (bug 1888)
2425 message(bformat(_("Document exported as %1$s"),
2426 formats.prettyName(format)));
2433 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2436 return doExport(format, put_in_tempdir, result_file);
2440 bool Buffer::preview(string const & format) const
2443 if (!doExport(format, true, result_file))
2445 return formats.view(*this, FileName(result_file), format);
2449 bool Buffer::isExportable(string const & format) const
2451 vector<string> backs = backends();
2452 for (vector<string>::const_iterator it = backs.begin();
2453 it != backs.end(); ++it)
2454 if (theConverters().isReachable(*it, format))
2460 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2462 vector<string> backs = backends();
2463 vector<Format const *> result =
2464 theConverters().getReachable(backs[0], only_viewable, true);
2465 for (vector<string>::const_iterator it = backs.begin() + 1;
2466 it != backs.end(); ++it) {
2467 vector<Format const *> r =
2468 theConverters().getReachable(*it, only_viewable, false);
2469 result.insert(result.end(), r.begin(), r.end());
2475 vector<string> Buffer::backends() const
2478 if (params().baseClass()->isTeXClassAvailable()) {
2479 v.push_back(bufferFormat());
2480 // FIXME: Don't hardcode format names here, but use a flag
2481 if (v.back() == "latex")
2482 v.push_back("pdflatex");
2484 v.push_back("text");
2490 bool Buffer::readFileHelper(FileName const & s)
2492 // File information about normal file
2494 docstring const file = makeDisplayPath(s.absFilename(), 50);
2495 docstring text = bformat(_("The specified document\n%1$s"
2496 "\ncould not be read."), file);
2497 Alert::error(_("Could not read document"), text);
2501 // Check if emergency save file exists and is newer.
2502 FileName const e(s.absFilename() + ".emergency");
2504 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2505 docstring const file = makeDisplayPath(s.absFilename(), 20);
2506 docstring const text =
2507 bformat(_("An emergency save of the document "
2509 "Recover emergency save?"), file);
2510 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2511 _("&Recover"), _("&Load Original"),
2515 // the file is not saved if we load the emergency file.
2525 // Now check if autosave file is newer.
2526 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2528 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2529 docstring const file = makeDisplayPath(s.absFilename(), 20);
2530 docstring const text =
2531 bformat(_("The backup of the document "
2532 "%1$s is newer.\n\nLoad the "
2533 "backup instead?"), file);
2534 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2535 _("&Load backup"), _("Load &original"),
2539 // the file is not saved if we load the autosave file.
2543 // Here we delete the autosave
2554 bool Buffer::loadLyXFile(FileName const & s)
2556 if (s.isReadableFile()) {
2557 if (readFileHelper(s)) {
2558 lyxvc().file_found_hook(s);
2559 if (!s.isWritable())
2564 docstring const file = makeDisplayPath(s.absFilename(), 20);
2565 // Here we probably should run
2566 if (LyXVC::file_not_found_hook(s)) {
2567 docstring const text =
2568 bformat(_("Do you want to retrieve the document"
2569 " %1$s from version control?"), file);
2570 int const ret = Alert::prompt(_("Retrieve from version control?"),
2571 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2574 // How can we know _how_ to do the checkout?
2575 // With the current VC support it has to be,
2576 // a RCS file since CVS do not have special ,v files.
2578 return loadLyXFile(s);
2586 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2588 TeXErrors::Errors::const_iterator cit = terr.begin();
2589 TeXErrors::Errors::const_iterator end = terr.end();
2591 for (; cit != end; ++cit) {
2594 int errorRow = cit->error_in_line;
2595 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2601 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2602 } while (found && id_start == id_end && pos_start == pos_end);
2604 errorList.push_back(ErrorItem(cit->error_desc,
2605 cit->error_text, id_start, pos_start, pos_end));