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 "DispatchResult.h"
28 #include "DocIterator.h"
30 #include "ErrorList.h"
33 #include "FuncRequest.h"
34 #include "FuncStatus.h"
35 #include "IndicesList.h"
36 #include "InsetIterator.h"
37 #include "InsetList.h"
39 #include "LaTeXFeatures.h"
43 #include "LyXAction.h"
47 #include "output_docbook.h"
49 #include "output_latex.h"
50 #include "output_xhtml.h"
51 #include "output_plaintext.h"
52 #include "Paragraph.h"
53 #include "ParagraphParameters.h"
54 #include "ParIterator.h"
55 #include "PDFOptions.h"
56 #include "SpellChecker.h"
59 #include "TexStream.h"
61 #include "TextClass.h"
62 #include "TocBackend.h"
64 #include "VCBackend.h"
66 #include "WordLangTuple.h"
69 #include "insets/InsetBibitem.h"
70 #include "insets/InsetBibtex.h"
71 #include "insets/InsetBranch.h"
72 #include "insets/InsetInclude.h"
73 #include "insets/InsetText.h"
75 #include "mathed/MacroTable.h"
76 #include "mathed/MathMacroTemplate.h"
77 #include "mathed/MathSupport.h"
79 #include "frontends/alert.h"
80 #include "frontends/Delegates.h"
81 #include "frontends/WorkAreaManager.h"
83 #include "graphics/Previews.h"
85 #include "support/lassert.h"
86 #include "support/convert.h"
87 #include "support/debug.h"
88 #include "support/docstring_list.h"
89 #include "support/ExceptionMessage.h"
90 #include "support/FileName.h"
91 #include "support/FileNameList.h"
92 #include "support/filetools.h"
93 #include "support/ForkedCalls.h"
94 #include "support/gettext.h"
95 #include "support/gzstream.h"
96 #include "support/lstrings.h"
97 #include "support/lyxalgo.h"
98 #include "support/os.h"
99 #include "support/Package.h"
100 #include "support/Path.h"
101 #include "support/Systemcall.h"
102 #include "support/textutils.h"
103 #include "support/types.h"
105 #include <boost/bind.hpp>
106 #include <boost/shared_ptr.hpp>
118 using namespace lyx::support;
122 namespace Alert = frontend::Alert;
123 namespace os = support::os;
127 // Do not remove the comment below, so we get merge conflict in
128 // independent branches. Instead add your own.
129 int const LYX_FORMAT = 370; // uwestoehr: option to suppress default date
131 typedef map<string, bool> DepClean;
132 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
134 void showPrintError(string const & name)
136 docstring str = bformat(_("Could not print the document %1$s.\n"
137 "Check that your printer is set up correctly."),
138 makeDisplayPath(name, 50));
139 Alert::error(_("Print document failed"), str);
144 class BufferSet : public std::set<Buffer const *> {};
149 Impl(Buffer & parent, FileName const & file, bool readonly);
163 mutable TexRow texrow;
165 /// need to regenerate .tex?
169 mutable bool lyx_clean;
171 /// is autosave needed?
172 mutable bool bak_clean;
174 /// is this a unnamed file (New...)?
180 /// name of the file the buffer is associated with.
183 /** Set to true only when the file is fully loaded.
184 * Used to prevent the premature generation of previews
185 * and by the citation inset.
187 bool file_fully_loaded;
190 mutable TocBackend toc_backend;
193 typedef pair<DocIterator, MacroData> ScopeMacro;
194 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
195 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
196 /// map from the macro name to the position map,
197 /// which maps the macro definition position to the scope and the MacroData.
198 NamePositionScopeMacroMap macros;
201 /// positions of child buffers in the buffer
202 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
203 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
204 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
205 /// position of children buffers in this buffer
206 BufferPositionMap children_positions;
207 /// map from children inclusion positions to their scope and their buffer
208 PositionScopeBufferMap position_to_children;
210 /// Container for all sort of Buffer dependant errors.
211 map<string, ErrorList> errorLists;
213 /// timestamp and checksum used to test if the file has been externally
214 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
216 unsigned long checksum_;
219 frontend::WorkAreaManager * wa_;
224 /// A cache for the bibfiles (including bibfiles of loaded child
225 /// documents), needed for appropriate update of natbib labels.
226 mutable support::FileNameList bibfilesCache_;
228 // FIXME The caching mechanism could be improved. At present, we have a
229 // cache for each Buffer, that caches all the bibliography info for that
230 // Buffer. A more efficient solution would be to have a global cache per
231 // file, and then to construct the Buffer's bibinfo from that.
232 /// A cache for bibliography info
233 mutable BiblioInfo bibinfo_;
234 /// whether the bibinfo cache is valid
235 bool bibinfoCacheValid_;
236 /// Cache of timestamps of .bib files
237 map<FileName, time_t> bibfileStatus_;
239 mutable RefCache ref_cache_;
241 /// our Text that should be wrapped in an InsetText
244 /// This is here to force the test to be done whenever parent_buffer
246 Buffer const * parent() const {
247 // if parent_buffer is not loaded, then it has been unloaded,
248 // which means that parent_buffer is an invalid pointer. So we
249 // set it to null in that case.
250 if (!theBufferList().isLoaded(parent_buffer))
252 return parent_buffer;
255 void setParent(Buffer const * pb) { parent_buffer = pb; }
257 /// So we can force access via the accessors.
258 mutable Buffer const * parent_buffer;
262 /// Creates the per buffer temporary directory
263 static FileName createBufferTmpDir()
266 // We are in our own directory. Why bother to mangle name?
267 // In fact I wrote this code to circumvent a problematic behaviour
268 // (bug?) of EMX mkstemp().
269 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
270 convert<string>(count++));
272 if (!tmpfl.createDirectory(0777)) {
273 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
274 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
275 from_utf8(tmpfl.absFilename())));
281 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
282 : lyx_clean(true), bak_clean(true), unnamed(false),
283 read_only(readonly_), filename(file), file_fully_loaded(false),
284 toc_backend(&parent), macro_lock(false), timestamp_(0),
285 checksum_(0), wa_(0), undo_(parent), bibinfoCacheValid_(false),
288 temppath = createBufferTmpDir();
289 lyxvc.setBuffer(&parent);
291 wa_ = new frontend::WorkAreaManager;
295 Buffer::Buffer(string const & file, bool readonly)
296 : d(new Impl(*this, FileName(file), readonly)), gui_(0)
298 LYXERR(Debug::INFO, "Buffer::Buffer()");
300 d->inset = new InsetText(*this);
301 d->inset->setAutoBreakRows(true);
302 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
308 LYXERR(Debug::INFO, "Buffer::~Buffer()");
309 // here the buffer should take care that it is
310 // saved properly, before it goes into the void.
312 // GuiView already destroyed
315 if (d->unnamed && d->filename.extension() == "internal") {
316 // No need to do additional cleanups for internal buffer.
321 // loop over children
322 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
323 Impl::BufferPositionMap::iterator end = d->children_positions.end();
324 for (; it != end; ++it) {
325 Buffer * child = const_cast<Buffer *>(it->first);
326 // The child buffer might have been closed already.
327 if (theBufferList().isLoaded(child))
328 theBufferList().releaseChild(this, child);
332 docstring msg = _("Buffer had unsaved changes when destroyed!\n");
333 msg += emergencyWrite();
334 frontend::Alert::warning(_("Attempting to destroy dirty Buffer!"), msg);
337 // clear references to children in macro tables
338 d->children_positions.clear();
339 d->position_to_children.clear();
341 if (!d->temppath.destroyDirectory()) {
342 Alert::warning(_("Could not remove temporary directory"),
343 bformat(_("Could not remove the temporary directory %1$s"),
344 from_utf8(d->temppath.absFilename())));
347 // Remove any previewed LaTeX snippets associated with this buffer.
348 thePreviews().removeLoader(*this);
354 void Buffer::changed() const
361 frontend::WorkAreaManager & Buffer::workAreaManager() const
363 LASSERT(d->wa_, /**/);
368 Text & Buffer::text() const
370 return d->inset->text();
374 Inset & Buffer::inset() const
380 BufferParams & Buffer::params()
386 BufferParams const & Buffer::params() const
392 ParagraphList & Buffer::paragraphs()
394 return text().paragraphs();
398 ParagraphList const & Buffer::paragraphs() const
400 return text().paragraphs();
404 LyXVC & Buffer::lyxvc()
410 LyXVC const & Buffer::lyxvc() const
416 string const Buffer::temppath() const
418 return d->temppath.absFilename();
422 TexRow & Buffer::texrow()
428 TexRow const & Buffer::texrow() const
434 TocBackend & Buffer::tocBackend() const
436 return d->toc_backend;
440 Undo & Buffer::undo()
446 string Buffer::latexName(bool const no_path) const
448 FileName latex_name =
449 makeLatexName(exportFileName());
450 return no_path ? latex_name.onlyFileName()
451 : latex_name.absFilename();
455 FileName Buffer::exportFileName() const
457 docstring const branch_suffix =
458 params().branchlist().getFilenameSuffix();
459 if (branch_suffix.empty())
462 string const name = fileName().onlyFileNameWithoutExt()
463 + to_utf8(branch_suffix);
464 FileName res(fileName().onlyPath().absFilename() + "/" + name);
465 res.changeExtension(fileName().extension());
471 string Buffer::logName(LogType * type) const
473 string const filename = latexName(false);
475 if (filename.empty()) {
481 string const path = temppath();
483 FileName const fname(addName(temppath(),
484 onlyFilename(changeExtension(filename,
487 // FIXME: how do we know this is the name of the build log?
488 FileName const bname(
489 addName(path, onlyFilename(
490 changeExtension(filename,
491 formats.extension(bufferFormat()) + ".out"))));
493 // Also consider the master buffer log file
494 FileName masterfname = fname;
496 if (masterBuffer() != this) {
497 string const mlogfile = masterBuffer()->logName(&mtype);
498 masterfname = FileName(mlogfile);
501 // If no Latex log or Build log is newer, show Build log
502 if (bname.exists() &&
503 ((!fname.exists() && !masterfname.exists())
504 || (fname.lastModified() < bname.lastModified()
505 && masterfname.lastModified() < bname.lastModified()))) {
506 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
509 return bname.absFilename();
510 // If we have a newer master file log or only a master log, show this
511 } else if (fname != masterfname
512 && (!fname.exists() && (masterfname.exists()
513 || fname.lastModified() < masterfname.lastModified()))) {
514 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
517 return masterfname.absFilename();
519 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
522 return fname.absFilename();
526 void Buffer::setReadonly(bool const flag)
528 if (d->read_only != flag) {
535 void Buffer::setFileName(string const & newfile)
537 d->filename = makeAbsPath(newfile);
538 setReadonly(d->filename.isReadOnly());
543 int Buffer::readHeader(Lexer & lex)
545 int unknown_tokens = 0;
547 int begin_header_line = -1;
549 // Initialize parameters that may be/go lacking in header:
550 params().branchlist().clear();
551 params().preamble.erase();
552 params().options.erase();
553 params().master.erase();
554 params().float_placement.erase();
555 params().paperwidth.erase();
556 params().paperheight.erase();
557 params().leftmargin.erase();
558 params().rightmargin.erase();
559 params().topmargin.erase();
560 params().bottommargin.erase();
561 params().headheight.erase();
562 params().headsep.erase();
563 params().footskip.erase();
564 params().columnsep.erase();
565 params().fontsCJK.erase();
566 params().listings_params.clear();
567 params().clearLayoutModules();
568 params().clearRemovedModules();
569 params().pdfoptions().clear();
570 params().indiceslist().clear();
571 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
573 for (int i = 0; i < 4; ++i) {
574 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
575 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
578 ErrorList & errorList = d->errorLists["Parse"];
587 if (token == "\\end_header")
591 if (token == "\\begin_header") {
592 begin_header_line = line;
596 LYXERR(Debug::PARSER, "Handling document header token: `"
599 string unknown = params().readToken(lex, token, d->filename.onlyPath());
600 if (!unknown.empty()) {
601 if (unknown[0] != '\\' && token == "\\textclass") {
602 Alert::warning(_("Unknown document class"),
603 bformat(_("Using the default document class, because the "
604 "class %1$s is unknown."), from_utf8(unknown)));
607 docstring const s = bformat(_("Unknown token: "
611 errorList.push_back(ErrorItem(_("Document header error"),
616 if (begin_header_line) {
617 docstring const s = _("\\begin_header is missing");
618 errorList.push_back(ErrorItem(_("Document header error"),
622 params().makeDocumentClass();
624 return unknown_tokens;
629 // changed to be public and have one parameter
630 // Returns true if "\end_document" is not read (Asger)
631 bool Buffer::readDocument(Lexer & lex)
633 ErrorList & errorList = d->errorLists["Parse"];
636 if (!lex.checkFor("\\begin_document")) {
637 docstring const s = _("\\begin_document is missing");
638 errorList.push_back(ErrorItem(_("Document header error"),
642 // we are reading in a brand new document
643 LASSERT(paragraphs().empty(), /**/);
647 if (params().outputChanges) {
648 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
649 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
650 LaTeXFeatures::isAvailable("xcolor");
652 if (!dvipost && !xcolorulem) {
653 Alert::warning(_("Changes not shown in LaTeX output"),
654 _("Changes will not be highlighted in LaTeX output, "
655 "because neither dvipost nor xcolor/ulem are installed.\n"
656 "Please install these packages or redefine "
657 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
658 } else if (!xcolorulem) {
659 Alert::warning(_("Changes not shown in LaTeX output"),
660 _("Changes will not be highlighted in LaTeX output "
661 "when using pdflatex, because xcolor and ulem are not installed.\n"
662 "Please install both packages or redefine "
663 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
667 if (!params().master.empty()) {
668 FileName const master_file = makeAbsPath(params().master,
669 onlyPath(absFileName()));
670 if (isLyXFilename(master_file.absFilename())) {
672 checkAndLoadLyXFile(master_file, true);
674 // necessary e.g. after a reload
675 // to re-register the child (bug 5873)
676 // FIXME: clean up updateMacros (here, only
677 // child registering is needed).
678 master->updateMacros();
679 // set master as master buffer, but only
680 // if we are a real child
681 if (master->isChild(this))
683 // if the master is not fully loaded
684 // it is probably just loading this
685 // child. No warning needed then.
686 else if (master->isFullyLoaded())
687 LYXERR0("The master '"
689 << "' assigned to this document ("
691 << ") does not include "
692 "this document. Ignoring the master assignment.");
697 // assure we have a default index
698 params().indiceslist().addDefault(B_("Index"));
701 bool const res = text().read(lex, errorList, d->inset);
704 updateMacroInstances();
709 bool Buffer::readString(string const & s)
711 params().compressed = false;
713 // remove dummy empty par
714 paragraphs().clear();
718 FileName const name = FileName::tempName("Buffer_readString");
719 switch (readFile(lex, name, true)) {
723 // We need to call lyx2lyx, so write the input to a file
724 ofstream os(name.toFilesystemEncoding().c_str());
727 return readFile(name);
737 bool Buffer::readFile(FileName const & filename)
739 FileName fname(filename);
741 params().compressed = fname.isZippedFile();
743 // remove dummy empty par
744 paragraphs().clear();
747 if (readFile(lex, fname) != success)
754 bool Buffer::isFullyLoaded() const
756 return d->file_fully_loaded;
760 void Buffer::setFullyLoaded(bool value)
762 d->file_fully_loaded = value;
766 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
769 LASSERT(!filename.empty(), /**/);
771 // the first (non-comment) token _must_ be...
772 if (!lex.checkFor("\\lyxformat")) {
773 Alert::error(_("Document format failure"),
774 bformat(_("%1$s is not a readable LyX document."),
775 from_utf8(filename.absFilename())));
781 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
782 // if present remove ".," from string.
783 size_t dot = tmp_format.find_first_of(".,");
784 //lyxerr << " dot found at " << dot << endl;
785 if (dot != string::npos)
786 tmp_format.erase(dot, 1);
787 int const file_format = convert<int>(tmp_format);
788 //lyxerr << "format: " << file_format << endl;
790 // save timestamp and checksum of the original disk file, making sure
791 // to not overwrite them with those of the file created in the tempdir
792 // when it has to be converted to the current format.
794 // Save the timestamp and checksum of disk file. If filename is an
795 // emergency file, save the timestamp and checksum of the original lyx file
796 // because isExternallyModified will check for this file. (BUG4193)
797 string diskfile = filename.absFilename();
798 if (suffixIs(diskfile, ".emergency"))
799 diskfile = diskfile.substr(0, diskfile.size() - 10);
800 saveCheckSum(FileName(diskfile));
803 if (file_format != LYX_FORMAT) {
806 // lyx2lyx would fail
809 FileName const tmpfile = FileName::tempName("Buffer_readFile");
810 if (tmpfile.empty()) {
811 Alert::error(_("Conversion failed"),
812 bformat(_("%1$s is from a different"
813 " version of LyX, but a temporary"
814 " file for converting it could"
816 from_utf8(filename.absFilename())));
819 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
820 if (lyx2lyx.empty()) {
821 Alert::error(_("Conversion script not found"),
822 bformat(_("%1$s is from a different"
823 " version of LyX, but the"
824 " conversion script lyx2lyx"
825 " could not be found."),
826 from_utf8(filename.absFilename())));
829 ostringstream command;
830 command << os::python()
831 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
832 << " -t " << convert<string>(LYX_FORMAT)
833 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
834 << ' ' << quoteName(filename.toFilesystemEncoding());
835 string const command_str = command.str();
837 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
839 cmd_ret const ret = runCommand(command_str);
840 if (ret.first != 0) {
841 Alert::error(_("Conversion script failed"),
842 bformat(_("%1$s is from a different version"
843 " of LyX, but the lyx2lyx script"
844 " failed to convert it."),
845 from_utf8(filename.absFilename())));
848 bool const ret = readFile(tmpfile);
849 // Do stuff with tmpfile name and buffer name here.
850 return ret ? success : failure;
855 if (readDocument(lex)) {
856 Alert::error(_("Document format failure"),
857 bformat(_("%1$s ended unexpectedly, which means"
858 " that it is probably corrupted."),
859 from_utf8(filename.absFilename())));
862 d->file_fully_loaded = true;
867 // Should probably be moved to somewhere else: BufferView? LyXView?
868 bool Buffer::save() const
870 // We don't need autosaves in the immediate future. (Asger)
871 resetAutosaveTimers();
873 string const encodedFilename = d->filename.toFilesystemEncoding();
876 bool madeBackup = false;
878 // make a backup if the file already exists
879 if (lyxrc.make_backup && fileName().exists()) {
880 backupName = FileName(absFileName() + '~');
881 if (!lyxrc.backupdir_path.empty()) {
882 string const mangledName =
883 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
884 backupName = FileName(addName(lyxrc.backupdir_path,
887 if (fileName().copyTo(backupName)) {
890 Alert::error(_("Backup failure"),
891 bformat(_("Cannot create backup file %1$s.\n"
892 "Please check whether the directory exists and is writeable."),
893 from_utf8(backupName.absFilename())));
894 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
898 // ask if the disk file has been externally modified (use checksum method)
899 if (fileName().exists() && isExternallyModified(checksum_method)) {
900 docstring const file = makeDisplayPath(absFileName(), 20);
901 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
902 "you want to overwrite this file?"), file);
903 int const ret = Alert::prompt(_("Overwrite modified file?"),
904 text, 1, 1, _("&Overwrite"), _("&Cancel"));
909 if (writeFile(d->filename)) {
913 // Saving failed, so backup is not backup
915 backupName.moveTo(d->filename);
921 bool Buffer::writeFile(FileName const & fname) const
923 if (d->read_only && fname == d->filename)
928 docstring const str = bformat(_("Saving document %1$s..."),
929 makeDisplayPath(fname.absFilename()));
932 if (params().compressed) {
933 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
934 retval = ofs && write(ofs);
936 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
937 retval = ofs && write(ofs);
941 message(str + _(" could not write file!"));
945 removeAutosaveFile();
947 saveCheckSum(d->filename);
948 message(str + _(" done."));
954 docstring Buffer::emergencyWrite()
956 // No need to save if the buffer has not changed.
960 string const doc = isUnnamed() ? onlyFilename(absFileName()) : absFileName();
962 docstring user_message = bformat(
963 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
965 // We try to save three places:
966 // 1) Same place as document. Unless it is an unnamed doc.
968 string s = absFileName();
971 if (writeFile(FileName(s))) {
973 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
976 user_message += _(" Save failed! Trying again...\n");
980 // 2) In HOME directory.
981 string s = addName(package().home_dir().absFilename(), absFileName());
983 lyxerr << ' ' << s << endl;
984 if (writeFile(FileName(s))) {
986 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
990 user_message += _(" Save failed! Trying yet again...\n");
992 // 3) In "/tmp" directory.
993 // MakeAbsPath to prepend the current
994 // drive letter on OS/2
995 s = addName(package().temp_dir().absFilename(), absFileName());
997 lyxerr << ' ' << s << endl;
998 if (writeFile(FileName(s))) {
1000 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1001 return user_message;
1004 user_message += _(" Save failed! Bummer. Document is lost.");
1007 return user_message;
1011 bool Buffer::write(ostream & ofs) const
1014 // Use the standard "C" locale for file output.
1015 ofs.imbue(locale::classic());
1018 // The top of the file should not be written by params().
1020 // write out a comment in the top of the file
1021 ofs << "#LyX " << lyx_version
1022 << " created this file. For more info see http://www.lyx.org/\n"
1023 << "\\lyxformat " << LYX_FORMAT << "\n"
1024 << "\\begin_document\n";
1026 /// For each author, set 'used' to true if there is a change
1027 /// by this author in the document; otherwise set it to 'false'.
1028 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1029 AuthorList::Authors::const_iterator a_end = params().authors().end();
1030 for (; a_it != a_end; ++a_it)
1031 a_it->setUsed(false);
1033 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1034 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1035 for ( ; it != end; ++it)
1036 it->checkAuthors(params().authors());
1038 // now write out the buffer parameters.
1039 ofs << "\\begin_header\n";
1040 params().writeFile(ofs);
1041 ofs << "\\end_header\n";
1044 ofs << "\n\\begin_body\n";
1046 ofs << "\n\\end_body\n";
1048 // Write marker that shows file is complete
1049 ofs << "\\end_document" << endl;
1051 // Shouldn't really be needed....
1054 // how to check if close went ok?
1055 // Following is an attempt... (BE 20001011)
1057 // good() returns false if any error occured, including some
1058 // formatting error.
1059 // bad() returns true if something bad happened in the buffer,
1060 // which should include file system full errors.
1065 lyxerr << "File was not closed properly." << endl;
1072 bool Buffer::makeLaTeXFile(FileName const & fname,
1073 string const & original_path,
1074 OutputParams const & runparams_in,
1075 bool output_preamble, bool output_body) const
1077 OutputParams runparams = runparams_in;
1078 if (params().useXetex)
1079 runparams.flavor = OutputParams::XETEX;
1081 string const encoding = runparams.encoding->iconvName();
1082 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1085 try { ofs.reset(encoding); }
1086 catch (iconv_codecvt_facet_exception & e) {
1087 lyxerr << "Caught iconv exception: " << e.what() << endl;
1088 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1089 "verify that the support software for your encoding (%1$s) is "
1090 "properly installed"), from_ascii(encoding)));
1093 if (!openFileWrite(ofs, fname))
1096 //TexStream ts(ofs.rdbuf(), &texrow());
1097 ErrorList & errorList = d->errorLists["Export"];
1099 bool failed_export = false;
1102 writeLaTeXSource(ofs, original_path,
1103 runparams, output_preamble, output_body);
1105 catch (EncodingException & e) {
1106 odocstringstream ods;
1107 ods.put(e.failed_char);
1109 oss << "0x" << hex << e.failed_char << dec;
1110 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1111 " (code point %2$s)"),
1112 ods.str(), from_utf8(oss.str()));
1113 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1114 "representable in the chosen encoding.\n"
1115 "Changing the document encoding to utf8 could help."),
1116 e.par_id, e.pos, e.pos + 1));
1117 failed_export = true;
1119 catch (iconv_codecvt_facet_exception & e) {
1120 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1121 _(e.what()), -1, 0, 0));
1122 failed_export = true;
1124 catch (exception const & e) {
1125 errorList.push_back(ErrorItem(_("conversion failed"),
1126 _(e.what()), -1, 0, 0));
1127 failed_export = true;
1130 lyxerr << "Caught some really weird exception..." << endl;
1136 failed_export = true;
1137 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1141 return !failed_export;
1145 void Buffer::writeLaTeXSource(odocstream & os,
1146 string const & original_path,
1147 OutputParams const & runparams_in,
1148 bool const output_preamble, bool const output_body) const
1150 // The child documents, if any, shall be already loaded at this point.
1152 OutputParams runparams = runparams_in;
1154 // Classify the unicode characters appearing in math insets
1155 Encodings::initUnicodeMath(*this);
1157 // validate the buffer.
1158 LYXERR(Debug::LATEX, " Validating buffer...");
1159 LaTeXFeatures features(*this, params(), runparams);
1161 LYXERR(Debug::LATEX, " Buffer validation done.");
1163 // The starting paragraph of the coming rows is the
1164 // first paragraph of the document. (Asger)
1165 if (output_preamble && runparams.nice) {
1166 os << "%% LyX " << lyx_version << " created this file. "
1167 "For more info, see http://www.lyx.org/.\n"
1168 "%% Do not edit unless you really know what "
1170 d->texrow.newline();
1171 d->texrow.newline();
1173 LYXERR(Debug::INFO, "lyx document header finished");
1175 // Don't move this behind the parent_buffer=0 code below,
1176 // because then the macros will not get the right "redefinition"
1177 // flag as they don't see the parent macros which are output before.
1180 // fold macros if possible, still with parent buffer as the
1181 // macros will be put in the prefix anyway.
1182 updateMacroInstances();
1184 // There are a few differences between nice LaTeX and usual files:
1185 // usual is \batchmode and has a
1186 // special input@path to allow the including of figures
1187 // with either \input or \includegraphics (what figinsets do).
1188 // input@path is set when the actual parameter
1189 // original_path is set. This is done for usual tex-file, but not
1190 // for nice-latex-file. (Matthias 250696)
1191 // Note that input@path is only needed for something the user does
1192 // in the preamble, included .tex files or ERT, files included by
1193 // LyX work without it.
1194 if (output_preamble) {
1195 if (!runparams.nice) {
1196 // code for usual, NOT nice-latex-file
1197 os << "\\batchmode\n"; // changed
1198 // from \nonstopmode
1199 d->texrow.newline();
1201 if (!original_path.empty()) {
1203 // We don't know the encoding of inputpath
1204 docstring const inputpath = from_utf8(latex_path(original_path));
1205 os << "\\makeatletter\n"
1206 << "\\def\\input@path{{"
1207 << inputpath << "/}}\n"
1208 << "\\makeatother\n";
1209 d->texrow.newline();
1210 d->texrow.newline();
1211 d->texrow.newline();
1214 // get parent macros (if this buffer has a parent) which will be
1215 // written at the document begin further down.
1216 MacroSet parentMacros;
1217 listParentMacros(parentMacros, features);
1219 // Write the preamble
1220 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1222 runparams.use_japanese = features.isRequired("japanese");
1228 os << "\\begin{document}\n";
1229 d->texrow.newline();
1231 // output the parent macros
1232 MacroSet::iterator it = parentMacros.begin();
1233 MacroSet::iterator end = parentMacros.end();
1234 for (; it != end; ++it)
1235 (*it)->write(os, true);
1236 } // output_preamble
1238 d->texrow.start(paragraphs().begin()->id(), 0);
1240 LYXERR(Debug::INFO, "preamble finished, now the body.");
1242 // if we are doing a real file with body, even if this is the
1243 // child of some other buffer, let's cut the link here.
1244 // This happens for example if only a child document is printed.
1245 Buffer const * save_parent = 0;
1246 if (output_preamble) {
1247 save_parent = d->parent();
1252 latexParagraphs(*this, text(), os, d->texrow, runparams);
1254 // Restore the parenthood if needed
1255 if (output_preamble)
1256 d->setParent(save_parent);
1258 // add this just in case after all the paragraphs
1260 d->texrow.newline();
1262 if (output_preamble) {
1263 os << "\\end{document}\n";
1264 d->texrow.newline();
1265 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1267 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1269 runparams_in.encoding = runparams.encoding;
1271 // Just to be sure. (Asger)
1272 d->texrow.newline();
1274 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1275 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1279 bool Buffer::isLatex() const
1281 return params().documentClass().outputType() == LATEX;
1285 bool Buffer::isLiterate() const
1287 return params().documentClass().outputType() == LITERATE;
1291 bool Buffer::isDocBook() const
1293 return params().documentClass().outputType() == DOCBOOK;
1297 void Buffer::makeDocBookFile(FileName const & fname,
1298 OutputParams const & runparams,
1299 bool const body_only) const
1301 LYXERR(Debug::LATEX, "makeDocBookFile...");
1304 if (!openFileWrite(ofs, fname))
1307 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1311 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1315 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1316 OutputParams const & runparams,
1317 bool const only_body) const
1319 LaTeXFeatures features(*this, params(), runparams);
1324 DocumentClass const & tclass = params().documentClass();
1325 string const top_element = tclass.latexname();
1328 if (runparams.flavor == OutputParams::XML)
1329 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1332 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1335 if (! tclass.class_header().empty())
1336 os << from_ascii(tclass.class_header());
1337 else if (runparams.flavor == OutputParams::XML)
1338 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1339 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1341 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1343 docstring preamble = from_utf8(params().preamble);
1344 if (runparams.flavor != OutputParams::XML ) {
1345 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1346 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1347 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1348 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1351 string const name = runparams.nice
1352 ? changeExtension(absFileName(), ".sgml") : fname;
1353 preamble += features.getIncludedFiles(name);
1354 preamble += features.getLyXSGMLEntities();
1356 if (!preamble.empty()) {
1357 os << "\n [ " << preamble << " ]";
1362 string top = top_element;
1364 if (runparams.flavor == OutputParams::XML)
1365 top += params().language->code();
1367 top += params().language->code().substr(0, 2);
1370 if (!params().options.empty()) {
1372 top += params().options;
1375 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1376 << " file was created by LyX " << lyx_version
1377 << "\n See http://www.lyx.org/ for more information -->\n";
1379 params().documentClass().counters().reset();
1383 sgml::openTag(os, top);
1385 docbookParagraphs(text(), *this, os, runparams);
1386 sgml::closeTag(os, top_element);
1390 void Buffer::makeLyXHTMLFile(FileName const & fname,
1391 OutputParams const & runparams,
1392 bool const body_only) const
1394 LYXERR(Debug::LATEX, "makeLYXHTMLFile...");
1397 if (!openFileWrite(ofs, fname))
1400 writeLyXHTMLSource(ofs, runparams, body_only);
1404 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1408 void Buffer::writeLyXHTMLSource(odocstream & os,
1409 OutputParams const & runparams,
1410 bool const only_body) const
1412 LaTeXFeatures features(*this, params(), runparams);
1418 os << "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"" <<
1419 " \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n";
1420 // FIXME Language should be set properly.
1421 os << "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\n";
1424 // FIXME Presumably need to set this right
1425 os << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1426 // FIXME Get this during validation? What about other meta-data?
1427 os << "<title>TBA</title>\n";
1429 os << features.getTClassHTMLPreamble();
1433 docstring const styleinfo = features.getTClassHTMLStyles();
1434 if (!styleinfo.empty()) {
1435 os << "<style type='text/css'>\n";
1439 os << "</head>\n<body>\n";
1442 params().documentClass().counters().reset();
1443 xhtmlParagraphs(text(), *this, os, runparams);
1445 os << "</body>\n</html>\n";
1449 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1450 // Other flags: -wall -v0 -x
1451 int Buffer::runChktex()
1455 // get LaTeX-Filename
1456 FileName const path(temppath());
1457 string const name = addName(path.absFilename(), latexName());
1458 string const org_path = filePath();
1460 PathChanger p(path); // path to LaTeX file
1461 message(_("Running chktex..."));
1463 // Generate the LaTeX file if neccessary
1464 OutputParams runparams(¶ms().encoding());
1465 runparams.flavor = OutputParams::LATEX;
1466 runparams.nice = false;
1467 makeLaTeXFile(FileName(name), org_path, runparams);
1470 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1471 int const res = chktex.run(terr); // run chktex
1474 Alert::error(_("chktex failure"),
1475 _("Could not run chktex successfully."));
1476 } else if (res > 0) {
1477 ErrorList & errlist = d->errorLists["ChkTeX"];
1479 bufferErrors(terr, errlist);
1490 void Buffer::validate(LaTeXFeatures & features) const
1492 params().validate(features);
1496 for_each(paragraphs().begin(), paragraphs().end(),
1497 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1499 if (lyxerr.debugging(Debug::LATEX)) {
1500 features.showStruct();
1505 void Buffer::getLabelList(vector<docstring> & list) const
1507 // If this is a child document, use the parent's list instead.
1508 Buffer const * const pbuf = d->parent();
1510 pbuf->getLabelList(list);
1515 Toc & toc = d->toc_backend.toc("label");
1516 TocIterator toc_it = toc.begin();
1517 TocIterator end = toc.end();
1518 for (; toc_it != end; ++toc_it) {
1519 if (toc_it->depth() == 0)
1520 list.push_back(toc_it->str());
1525 void Buffer::updateBibfilesCache(UpdateScope scope) const
1527 // If this is a child document, use the parent's cache instead.
1528 Buffer const * const pbuf = d->parent();
1529 if (pbuf && scope != UpdateChildOnly) {
1530 pbuf->updateBibfilesCache();
1534 d->bibfilesCache_.clear();
1535 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1536 if (it->lyxCode() == BIBTEX_CODE) {
1537 InsetBibtex const & inset =
1538 static_cast<InsetBibtex const &>(*it);
1539 support::FileNameList const bibfiles = inset.getBibFiles();
1540 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1543 } else if (it->lyxCode() == INCLUDE_CODE) {
1544 InsetInclude & inset =
1545 static_cast<InsetInclude &>(*it);
1546 inset.updateBibfilesCache();
1547 support::FileNameList const & bibfiles =
1548 inset.getBibfilesCache();
1549 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1554 // the bibinfo cache is now invalid
1555 d->bibinfoCacheValid_ = false;
1559 void Buffer::invalidateBibinfoCache()
1561 d->bibinfoCacheValid_ = false;
1565 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1567 // If this is a child document, use the parent's cache instead.
1568 Buffer const * const pbuf = d->parent();
1569 if (pbuf && scope != UpdateChildOnly)
1570 return pbuf->getBibfilesCache();
1572 // We update the cache when first used instead of at loading time.
1573 if (d->bibfilesCache_.empty())
1574 const_cast<Buffer *>(this)->updateBibfilesCache(scope);
1576 return d->bibfilesCache_;
1580 BiblioInfo const & Buffer::masterBibInfo() const
1582 // if this is a child document and the parent is already loaded
1583 // use the parent's list instead [ale990412]
1584 Buffer const * const tmp = masterBuffer();
1587 return tmp->masterBibInfo();
1588 return localBibInfo();
1592 BiblioInfo const & Buffer::localBibInfo() const
1594 if (d->bibinfoCacheValid_) {
1595 support::FileNameList const & bibfilesCache = getBibfilesCache();
1596 // compare the cached timestamps with the actual ones.
1597 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1598 support::FileNameList::const_iterator en = bibfilesCache.end();
1599 for (; ei != en; ++ ei) {
1600 time_t lastw = ei->lastModified();
1601 if (lastw != d->bibfileStatus_[*ei]) {
1602 d->bibinfoCacheValid_ = false;
1603 d->bibfileStatus_[*ei] = lastw;
1609 if (!d->bibinfoCacheValid_) {
1610 d->bibinfo_.clear();
1611 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1612 it->fillWithBibKeys(d->bibinfo_, it);
1613 d->bibinfoCacheValid_ = true;
1619 bool Buffer::isDepClean(string const & name) const
1621 DepClean::const_iterator const it = d->dep_clean.find(name);
1622 if (it == d->dep_clean.end())
1628 void Buffer::markDepClean(string const & name)
1630 d->dep_clean[name] = true;
1634 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1636 switch (cmd.action) {
1637 case LFUN_BUFFER_EXPORT: {
1638 docstring const arg = cmd.argument();
1639 bool enable = arg == "custom" || isExportable(to_utf8(arg));
1641 flag.message(bformat(
1642 _("Don't know how to export to format: %1$s"), arg));
1643 flag.setEnabled(enable);
1647 case LFUN_BRANCH_ACTIVATE:
1648 case LFUN_BRANCH_DEACTIVATE: {
1649 BranchList const & branchList = params().branchlist();
1650 docstring const branchName = cmd.argument();
1651 flag.setEnabled(!branchName.empty()
1652 && branchList.find(branchName));
1656 case LFUN_BRANCH_ADD:
1657 case LFUN_BRANCHES_RENAME:
1658 case LFUN_BUFFER_PRINT:
1659 // if no Buffer is present, then of course we won't be called!
1660 flag.setEnabled(true);
1670 void Buffer::dispatch(string const & command, DispatchResult & result)
1672 return dispatch(lyxaction.lookupFunc(command), result);
1676 // NOTE We can end up here even if we have no GUI, because we are called
1677 // by LyX::exec to handled command-line requests. So we may need to check
1678 // whether we have a GUI or not. The boolean use_gui holds this information.
1679 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
1681 // We'll set this back to false if need be.
1682 bool dispatched = true;
1684 switch (func.action) {
1685 case LFUN_BUFFER_EXPORT: {
1686 bool success = doExport(to_utf8(func.argument()), false);
1687 dr.setError(success);
1689 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
1694 case LFUN_BRANCH_ADD: {
1695 BranchList & branchList = params().branchlist();
1696 docstring const branchName = func.argument();
1697 if (branchName.empty()) {
1701 Branch * branch = branchList.find(branchName);
1703 LYXERR0("Branch " << branchName << " does already exist.");
1705 docstring const msg =
1706 bformat(_("Branch \"%1$s\" does already exist."), branchName);
1709 branchList.add(branchName);
1711 dr.update(Update::Force);
1716 case LFUN_BRANCH_ACTIVATE:
1717 case LFUN_BRANCH_DEACTIVATE: {
1718 BranchList & branchList = params().branchlist();
1719 docstring const branchName = func.argument();
1720 // the case without a branch name is handled elsewhere
1721 if (branchName.empty()) {
1725 Branch * branch = branchList.find(branchName);
1727 LYXERR0("Branch " << branchName << " does not exist.");
1729 docstring const msg =
1730 bformat(_("Branch \"%1$s\" does not exist."), branchName);
1733 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1735 dr.update(Update::Force);
1740 case LFUN_BRANCHES_RENAME: {
1741 if (func.argument().empty())
1744 docstring const oldname = from_utf8(func.getArg(0));
1745 docstring const newname = from_utf8(func.getArg(1));
1746 InsetIterator it = inset_iterator_begin(inset());
1747 InsetIterator const end = inset_iterator_end(inset());
1748 bool success = false;
1749 for (; it != end; ++it) {
1750 if (it->lyxCode() == BRANCH_CODE) {
1751 InsetBranch & ins = static_cast<InsetBranch &>(*it);
1752 if (ins.branch() == oldname) {
1753 undo().recordUndo(it);
1754 ins.rename(newname);
1759 if (it->lyxCode() == INCLUDE_CODE) {
1760 // get buffer of external file
1761 InsetInclude const & ins =
1762 static_cast<InsetInclude const &>(*it);
1763 Buffer * child = ins.getChildBuffer();
1766 child->dispatch(func, dr);
1771 dr.update(Update::Force);
1775 case LFUN_BUFFER_PRINT: {
1776 // we'll assume there's a problem until we succeed
1778 string target = func.getArg(0);
1779 string target_name = func.getArg(1);
1780 string command = func.getArg(2);
1783 || target_name.empty()
1784 || command.empty()) {
1785 LYXERR0("Unable to parse " << func.argument());
1786 docstring const msg =
1787 bformat(_("Unable to parse \"%1$s\""), func.argument());
1791 if (target != "printer" && target != "file") {
1792 LYXERR0("Unrecognized target \"" << target << '"');
1793 docstring const msg =
1794 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
1799 if (!doExport("dvi", true)) {
1800 showPrintError(absFileName());
1801 dr.setMessage(_("Error exporting to DVI."));
1805 // Push directory path.
1806 string const path = temppath();
1807 // Prevent the compiler from optimizing away p
1811 // there are three cases here:
1812 // 1. we print to a file
1813 // 2. we print directly to a printer
1814 // 3. we print using a spool command (print to file first)
1817 string const dviname = changeExtension(latexName(true), "dvi");
1819 if (target == "printer") {
1820 if (!lyxrc.print_spool_command.empty()) {
1821 // case 3: print using a spool
1822 string const psname = changeExtension(dviname,".ps");
1823 command += ' ' + lyxrc.print_to_file
1826 + quoteName(dviname);
1828 string command2 = lyxrc.print_spool_command + ' ';
1829 if (target_name != "default") {
1830 command2 += lyxrc.print_spool_printerprefix
1834 command2 += quoteName(psname);
1836 // If successful, then spool command
1837 res = one.startscript(Systemcall::Wait, command);
1840 // If there's no GUI, we have to wait on this command. Otherwise,
1841 // LyX deletes the temporary directory, and with it the spooled
1842 // file, before it can be printed!!
1843 Systemcall::Starttype stype = use_gui ?
1844 Systemcall::DontWait : Systemcall::Wait;
1845 res = one.startscript(stype, command2);
1848 // case 2: print directly to a printer
1849 if (target_name != "default")
1850 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
1852 Systemcall::Starttype stype = use_gui ?
1853 Systemcall::DontWait : Systemcall::Wait;
1854 res = one.startscript(stype, command + quoteName(dviname));
1858 // case 1: print to a file
1859 FileName const filename(makeAbsPath(target_name, filePath()));
1860 FileName const dvifile(makeAbsPath(dviname, path));
1861 if (filename.exists()) {
1862 docstring text = bformat(
1863 _("The file %1$s already exists.\n\n"
1864 "Do you want to overwrite that file?"),
1865 makeDisplayPath(filename.absFilename()));
1866 if (Alert::prompt(_("Overwrite file?"),
1867 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
1870 command += ' ' + lyxrc.print_to_file
1871 + quoteName(filename.toFilesystemEncoding())
1873 + quoteName(dvifile.toFilesystemEncoding());
1875 Systemcall::Starttype stype = use_gui ?
1876 Systemcall::DontWait : Systemcall::Wait;
1877 res = one.startscript(stype, command);
1883 dr.setMessage(_("Error running external commands."));
1884 showPrintError(absFileName());
1893 dr.dispatched(dispatched);
1897 void Buffer::changeLanguage(Language const * from, Language const * to)
1899 LASSERT(from, /**/);
1902 for_each(par_iterator_begin(),
1904 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1908 bool Buffer::isMultiLingual() const
1910 ParConstIterator end = par_iterator_end();
1911 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1912 if (it->isMultiLingual(params()))
1919 DocIterator Buffer::getParFromID(int const id) const
1921 Buffer * buf = const_cast<Buffer *>(this);
1923 // John says this is called with id == -1 from undo
1924 lyxerr << "getParFromID(), id: " << id << endl;
1925 return doc_iterator_end(buf);
1928 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
1929 if (it.paragraph().id() == id)
1932 return doc_iterator_end(buf);
1936 bool Buffer::hasParWithID(int const id) const
1938 return !getParFromID(id).atEnd();
1942 ParIterator Buffer::par_iterator_begin()
1944 return ParIterator(doc_iterator_begin(this));
1948 ParIterator Buffer::par_iterator_end()
1950 return ParIterator(doc_iterator_end(this));
1954 ParConstIterator Buffer::par_iterator_begin() const
1956 return ParConstIterator(doc_iterator_begin(this));
1960 ParConstIterator Buffer::par_iterator_end() const
1962 return ParConstIterator(doc_iterator_end(this));
1966 Language const * Buffer::language() const
1968 return params().language;
1972 docstring const Buffer::B_(string const & l10n) const
1974 return params().B_(l10n);
1978 bool Buffer::isClean() const
1980 return d->lyx_clean;
1984 bool Buffer::isBakClean() const
1986 return d->bak_clean;
1990 bool Buffer::isExternallyModified(CheckMethod method) const
1992 LASSERT(d->filename.exists(), /**/);
1993 // if method == timestamp, check timestamp before checksum
1994 return (method == checksum_method
1995 || d->timestamp_ != d->filename.lastModified())
1996 && d->checksum_ != d->filename.checksum();
2000 void Buffer::saveCheckSum(FileName const & file) const
2002 if (file.exists()) {
2003 d->timestamp_ = file.lastModified();
2004 d->checksum_ = file.checksum();
2006 // in the case of save to a new file.
2013 void Buffer::markClean() const
2015 if (!d->lyx_clean) {
2016 d->lyx_clean = true;
2019 // if the .lyx file has been saved, we don't need an
2021 d->bak_clean = true;
2025 void Buffer::markBakClean() const
2027 d->bak_clean = true;
2031 void Buffer::setUnnamed(bool flag)
2037 bool Buffer::isUnnamed() const
2043 // FIXME: this function should be moved to buffer_pimpl.C
2044 void Buffer::markDirty()
2047 d->lyx_clean = false;
2050 d->bak_clean = false;
2052 DepClean::iterator it = d->dep_clean.begin();
2053 DepClean::const_iterator const end = d->dep_clean.end();
2055 for (; it != end; ++it)
2060 FileName Buffer::fileName() const
2066 string Buffer::absFileName() const
2068 return d->filename.absFilename();
2072 string Buffer::filePath() const
2074 return d->filename.onlyPath().absFilename() + "/";
2078 bool Buffer::isReadonly() const
2080 return d->read_only;
2084 void Buffer::setParent(Buffer const * buffer)
2086 // Avoids recursive include.
2087 d->setParent(buffer == this ? 0 : buffer);
2092 Buffer const * Buffer::parent() const
2098 void Buffer::collectRelatives(BufferSet & bufs) const
2102 parent()->collectRelatives(bufs);
2104 // loop over children
2105 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2106 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2107 for (; it != end; ++it)
2108 bufs.insert(const_cast<Buffer *>(it->first));
2112 std::vector<Buffer const *> Buffer::allRelatives() const
2115 collectRelatives(bufs);
2116 BufferSet::iterator it = bufs.begin();
2117 std::vector<Buffer const *> ret;
2118 for (; it != bufs.end(); ++it)
2124 Buffer const * Buffer::masterBuffer() const
2126 Buffer const * const pbuf = d->parent();
2130 return pbuf->masterBuffer();
2134 bool Buffer::isChild(Buffer * child) const
2136 return d->children_positions.find(child) != d->children_positions.end();
2140 DocIterator Buffer::firstChildPosition(Buffer const * child)
2142 Impl::BufferPositionMap::iterator it;
2143 it = d->children_positions.find(child);
2144 if (it == d->children_positions.end())
2145 return DocIterator(this);
2150 std::vector<Buffer *> Buffer::getChildren() const
2152 std::vector<Buffer *> clist;
2153 // loop over children
2154 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2155 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2156 for (; it != end; ++it) {
2157 Buffer * child = const_cast<Buffer *>(it->first);
2158 clist.push_back(child);
2159 // there might be grandchildren
2160 std::vector<Buffer *> glist = child->getChildren();
2161 for (vector<Buffer *>::const_iterator git = glist.begin();
2162 git != glist.end(); ++git)
2163 clist.push_back(*git);
2169 template<typename M>
2170 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
2175 typename M::iterator it = m.lower_bound(x);
2176 if (it == m.begin())
2184 MacroData const * Buffer::getBufferMacro(docstring const & name,
2185 DocIterator const & pos) const
2187 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2189 // if paragraphs have no macro context set, pos will be empty
2193 // we haven't found anything yet
2194 DocIterator bestPos = par_iterator_begin();
2195 MacroData const * bestData = 0;
2197 // find macro definitions for name
2198 Impl::NamePositionScopeMacroMap::iterator nameIt
2199 = d->macros.find(name);
2200 if (nameIt != d->macros.end()) {
2201 // find last definition in front of pos or at pos itself
2202 Impl::PositionScopeMacroMap::const_iterator it
2203 = greatest_below(nameIt->second, pos);
2204 if (it != nameIt->second.end()) {
2206 // scope ends behind pos?
2207 if (pos < it->second.first) {
2208 // Looks good, remember this. If there
2209 // is no external macro behind this,
2210 // we found the right one already.
2211 bestPos = it->first;
2212 bestData = &it->second.second;
2216 // try previous macro if there is one
2217 if (it == nameIt->second.begin())
2224 // find macros in included files
2225 Impl::PositionScopeBufferMap::const_iterator it
2226 = greatest_below(d->position_to_children, pos);
2227 if (it == d->position_to_children.end())
2228 // no children before
2232 // do we know something better (i.e. later) already?
2233 if (it->first < bestPos )
2236 // scope ends behind pos?
2237 if (pos < it->second.first) {
2238 // look for macro in external file
2239 d->macro_lock = true;
2240 MacroData const * data
2241 = it->second.second->getMacro(name, false);
2242 d->macro_lock = false;
2244 bestPos = it->first;
2250 // try previous file if there is one
2251 if (it == d->position_to_children.begin())
2256 // return the best macro we have found
2261 MacroData const * Buffer::getMacro(docstring const & name,
2262 DocIterator const & pos, bool global) const
2267 // query buffer macros
2268 MacroData const * data = getBufferMacro(name, pos);
2272 // If there is a master buffer, query that
2273 Buffer const * const pbuf = d->parent();
2275 d->macro_lock = true;
2276 MacroData const * macro = pbuf->getMacro(
2277 name, *this, false);
2278 d->macro_lock = false;
2284 data = MacroTable::globalMacros().get(name);
2293 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2295 // set scope end behind the last paragraph
2296 DocIterator scope = par_iterator_begin();
2297 scope.pit() = scope.lastpit() + 1;
2299 return getMacro(name, scope, global);
2303 MacroData const * Buffer::getMacro(docstring const & name,
2304 Buffer const & child, bool global) const
2306 // look where the child buffer is included first
2307 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2308 if (it == d->children_positions.end())
2311 // check for macros at the inclusion position
2312 return getMacro(name, it->second, global);
2316 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
2318 pit_type lastpit = it.lastpit();
2320 // look for macros in each paragraph
2321 while (it.pit() <= lastpit) {
2322 Paragraph & par = it.paragraph();
2324 // iterate over the insets of the current paragraph
2325 InsetList const & insets = par.insetList();
2326 InsetList::const_iterator iit = insets.begin();
2327 InsetList::const_iterator end = insets.end();
2328 for (; iit != end; ++iit) {
2329 it.pos() = iit->pos;
2331 // is it a nested text inset?
2332 if (iit->inset->asInsetText()) {
2333 // Inset needs its own scope?
2334 InsetText const * itext = iit->inset->asInsetText();
2335 bool newScope = itext->isMacroScope();
2337 // scope which ends just behind the inset
2338 DocIterator insetScope = it;
2341 // collect macros in inset
2342 it.push_back(CursorSlice(*iit->inset));
2343 updateMacros(it, newScope ? insetScope : scope);
2348 // is it an external file?
2349 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2350 // get buffer of external file
2351 InsetInclude const & inset =
2352 static_cast<InsetInclude const &>(*iit->inset);
2353 d->macro_lock = true;
2354 Buffer * child = inset.getChildBuffer();
2355 d->macro_lock = false;
2359 // register its position, but only when it is
2360 // included first in the buffer
2361 if (d->children_positions.find(child) ==
2362 d->children_positions.end())
2363 d->children_positions[child] = it;
2365 // register child with its scope
2366 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
2370 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2374 MathMacroTemplate & macroTemplate =
2375 static_cast<MathMacroTemplate &>(*iit->inset);
2376 MacroContext mc(*this, it);
2377 macroTemplate.updateToContext(mc);
2380 bool valid = macroTemplate.validMacro();
2381 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2382 // then the BufferView's cursor will be invalid in
2383 // some cases which leads to crashes.
2388 d->macros[macroTemplate.name()][it] =
2389 Impl::ScopeMacro(scope, MacroData(*this, it));
2399 void Buffer::updateMacros() const
2404 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2406 // start with empty table
2408 d->children_positions.clear();
2409 d->position_to_children.clear();
2411 // Iterate over buffer, starting with first paragraph
2412 // The scope must be bigger than any lookup DocIterator
2413 // later. For the global lookup, lastpit+1 is used, hence
2414 // we use lastpit+2 here.
2415 DocIterator it = par_iterator_begin();
2416 DocIterator outerScope = it;
2417 outerScope.pit() = outerScope.lastpit() + 2;
2418 updateMacros(it, outerScope);
2422 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2424 InsetIterator it = inset_iterator_begin(inset());
2425 InsetIterator const end = inset_iterator_end(inset());
2426 for (; it != end; ++it) {
2427 if (it->lyxCode() == BRANCH_CODE) {
2428 InsetBranch & br = static_cast<InsetBranch &>(*it);
2429 docstring const name = br.branch();
2430 if (!from_master && !params().branchlist().find(name))
2431 result.push_back(name);
2432 else if (from_master && !masterBuffer()->params().branchlist().find(name))
2433 result.push_back(name);
2436 if (it->lyxCode() == INCLUDE_CODE) {
2437 // get buffer of external file
2438 InsetInclude const & ins =
2439 static_cast<InsetInclude const &>(*it);
2440 Buffer * child = ins.getChildBuffer();
2443 child->getUsedBranches(result, true);
2446 // remove duplicates
2451 void Buffer::updateMacroInstances() const
2453 LYXERR(Debug::MACROS, "updateMacroInstances for "
2454 << d->filename.onlyFileName());
2455 DocIterator it = doc_iterator_begin(this);
2456 DocIterator end = doc_iterator_end(this);
2457 for (; it != end; it.forwardPos()) {
2458 // look for MathData cells in InsetMathNest insets
2459 Inset * inset = it.nextInset();
2463 InsetMath * minset = inset->asInsetMath();
2467 // update macro in all cells of the InsetMathNest
2468 DocIterator::idx_type n = minset->nargs();
2469 MacroContext mc = MacroContext(*this, it);
2470 for (DocIterator::idx_type i = 0; i < n; ++i) {
2471 MathData & data = minset->cell(i);
2472 data.updateMacros(0, mc);
2478 void Buffer::listMacroNames(MacroNameSet & macros) const
2483 d->macro_lock = true;
2485 // loop over macro names
2486 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2487 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2488 for (; nameIt != nameEnd; ++nameIt)
2489 macros.insert(nameIt->first);
2491 // loop over children
2492 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2493 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2494 for (; it != end; ++it)
2495 it->first->listMacroNames(macros);
2498 Buffer const * const pbuf = d->parent();
2500 pbuf->listMacroNames(macros);
2502 d->macro_lock = false;
2506 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2508 Buffer const * const pbuf = d->parent();
2513 pbuf->listMacroNames(names);
2516 MacroNameSet::iterator it = names.begin();
2517 MacroNameSet::iterator end = names.end();
2518 for (; it != end; ++it) {
2520 MacroData const * data =
2521 pbuf->getMacro(*it, *this, false);
2523 macros.insert(data);
2525 // we cannot access the original MathMacroTemplate anymore
2526 // here to calls validate method. So we do its work here manually.
2527 // FIXME: somehow make the template accessible here.
2528 if (data->optionals() > 0)
2529 features.require("xargs");
2535 Buffer::References & Buffer::references(docstring const & label)
2538 return const_cast<Buffer *>(masterBuffer())->references(label);
2540 RefCache::iterator it = d->ref_cache_.find(label);
2541 if (it != d->ref_cache_.end())
2542 return it->second.second;
2544 static InsetLabel const * dummy_il = 0;
2545 static References const dummy_refs;
2546 it = d->ref_cache_.insert(
2547 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2548 return it->second.second;
2552 Buffer::References const & Buffer::references(docstring const & label) const
2554 return const_cast<Buffer *>(this)->references(label);
2558 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2560 masterBuffer()->d->ref_cache_[label].first = il;
2564 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2566 return masterBuffer()->d->ref_cache_[label].first;
2570 void Buffer::clearReferenceCache() const
2573 d->ref_cache_.clear();
2577 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2580 //FIXME: This does not work for child documents yet.
2581 LASSERT(code == CITE_CODE, /**/);
2582 // Check if the label 'from' appears more than once
2583 vector<docstring> labels;
2585 BiblioInfo const & keys = masterBibInfo();
2586 BiblioInfo::const_iterator bit = keys.begin();
2587 BiblioInfo::const_iterator bend = keys.end();
2589 for (; bit != bend; ++bit)
2591 labels.push_back(bit->first);
2594 if (count(labels.begin(), labels.end(), from) > 1)
2597 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2598 if (it->lyxCode() == code) {
2599 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2600 docstring const oldValue = inset.getParam(paramName);
2601 if (oldValue == from)
2602 inset.setParam(paramName, to);
2608 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2609 pit_type par_end, bool full_source) const
2611 OutputParams runparams(¶ms().encoding());
2612 runparams.nice = true;
2613 runparams.flavor = params().useXetex ?
2614 OutputParams::XETEX : OutputParams::LATEX;
2615 runparams.linelen = lyxrc.plaintext_linelen;
2616 // No side effect of file copying and image conversion
2617 runparams.dryrun = true;
2620 os << "% " << _("Preview source code") << "\n\n";
2622 d->texrow.newline();
2623 d->texrow.newline();
2625 writeDocBookSource(os, absFileName(), runparams, false);
2627 // latex or literate
2628 writeLaTeXSource(os, string(), runparams, true, true);
2630 runparams.par_begin = par_begin;
2631 runparams.par_end = par_end;
2632 if (par_begin + 1 == par_end) {
2634 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2638 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2639 convert<docstring>(par_begin),
2640 convert<docstring>(par_end - 1))
2647 // output paragraphs
2649 docbookParagraphs(text(), *this, os, runparams);
2651 // latex or literate
2652 latexParagraphs(*this, text(), os, texrow, runparams);
2657 ErrorList & Buffer::errorList(string const & type) const
2659 static ErrorList emptyErrorList;
2660 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2661 if (I == d->errorLists.end())
2662 return emptyErrorList;
2668 void Buffer::updateTocItem(std::string const & type,
2669 DocIterator const & dit) const
2672 gui_->updateTocItem(type, dit);
2676 void Buffer::structureChanged() const
2679 gui_->structureChanged();
2683 void Buffer::errors(string const & err, bool from_master) const
2686 gui_->errors(err, from_master);
2690 void Buffer::message(docstring const & msg) const
2697 void Buffer::setBusy(bool on) const
2704 void Buffer::setReadOnly(bool on) const
2707 d->wa_->setReadOnly(on);
2711 void Buffer::updateTitles() const
2714 d->wa_->updateTitles();
2718 void Buffer::resetAutosaveTimers() const
2721 gui_->resetAutosaveTimers();
2725 bool Buffer::hasGuiDelegate() const
2731 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2740 class AutoSaveBuffer : public ForkedProcess {
2743 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2744 : buffer_(buffer), fname_(fname) {}
2746 virtual boost::shared_ptr<ForkedProcess> clone() const
2748 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2753 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2754 from_utf8(fname_.absFilename())));
2755 return run(DontWait);
2759 virtual int generateChild();
2761 Buffer const & buffer_;
2766 int AutoSaveBuffer::generateChild()
2768 // tmp_ret will be located (usually) in /tmp
2769 // will that be a problem?
2770 // Note that this calls ForkedCalls::fork(), so it's
2771 // ok cross-platform.
2772 pid_t const pid = fork();
2773 // If you want to debug the autosave
2774 // you should set pid to -1, and comment out the fork.
2775 if (pid != 0 && pid != -1)
2778 // pid = -1 signifies that lyx was unable
2779 // to fork. But we will do the save
2781 bool failed = false;
2782 FileName const tmp_ret = FileName::tempName("lyxauto");
2783 if (!tmp_ret.empty()) {
2784 buffer_.writeFile(tmp_ret);
2785 // assume successful write of tmp_ret
2786 if (!tmp_ret.moveTo(fname_))
2792 // failed to write/rename tmp_ret so try writing direct
2793 if (!buffer_.writeFile(fname_)) {
2794 // It is dangerous to do this in the child,
2795 // but safe in the parent, so...
2796 if (pid == -1) // emit message signal.
2797 buffer_.message(_("Autosave failed!"));
2801 if (pid == 0) // we are the child so...
2810 FileName Buffer::getAutosaveFilename() const
2812 // if the document is unnamed try to save in the backup dir, else
2813 // in the default document path, and as a last try in the filePath,
2814 // which will most often be the temporary directory
2817 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
2818 : lyxrc.backupdir_path;
2819 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
2822 string const fname = "#" + d->filename.onlyFileName() + "#";
2823 return makeAbsPath(fname, fpath);
2827 void Buffer::removeAutosaveFile() const
2829 FileName const f = getAutosaveFilename();
2835 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
2837 FileName const newauto = getAutosaveFilename();
2838 if (!(oldauto == newauto || oldauto.moveTo(newauto)))
2839 LYXERR0("Unable to remove autosave file `" << oldauto << "'!");
2843 // Perfect target for a thread...
2844 void Buffer::autoSave() const
2846 if (isBakClean() || isReadonly()) {
2847 // We don't save now, but we'll try again later
2848 resetAutosaveTimers();
2852 // emit message signal.
2853 message(_("Autosaving current document..."));
2854 AutoSaveBuffer autosave(*this, getAutosaveFilename());
2858 resetAutosaveTimers();
2862 string Buffer::bufferFormat() const
2864 string format = params().documentClass().outputFormat();
2865 if (format == "latex") {
2866 if (params().useXetex)
2868 if (params().encoding().package() == Encoding::japanese)
2875 string Buffer::getDefaultOutputFormat() const
2877 if (!params().defaultOutputFormat.empty()
2878 && params().defaultOutputFormat != "default")
2879 return params().defaultOutputFormat;
2880 typedef vector<Format const *> Formats;
2881 Formats formats = exportableFormats(true);
2884 || params().useXetex
2885 || params().encoding().package() == Encoding::japanese) {
2886 if (formats.empty())
2888 // return the first we find
2889 return formats.front()->name();
2891 return lyxrc.default_view_format;
2896 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2897 string & result_file) const
2899 string backend_format;
2900 OutputParams runparams(¶ms().encoding());
2901 runparams.flavor = OutputParams::LATEX;
2902 runparams.linelen = lyxrc.plaintext_linelen;
2903 vector<string> backs = backends();
2904 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2905 // Get shortest path to format
2906 Graph::EdgePath path;
2907 for (vector<string>::const_iterator it = backs.begin();
2908 it != backs.end(); ++it) {
2909 Graph::EdgePath p = theConverters().getPath(*it, format);
2910 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2911 backend_format = *it;
2916 runparams.flavor = theConverters().getFlavor(path);
2918 Alert::error(_("Couldn't export file"),
2919 bformat(_("No information for exporting the format %1$s."),
2920 formats.prettyName(format)));
2924 backend_format = format;
2925 // FIXME: Don't hardcode format names here, but use a flag
2926 if (backend_format == "pdflatex")
2927 runparams.flavor = OutputParams::PDFLATEX;
2930 string filename = latexName(false);
2931 filename = addName(temppath(), filename);
2932 filename = changeExtension(filename,
2933 formats.extension(backend_format));
2936 updateMacroInstances();
2938 // Plain text backend
2939 if (backend_format == "text")
2940 writePlaintextFile(*this, FileName(filename), runparams);
2942 else if (backend_format == "xhtml")
2943 makeLyXHTMLFile(FileName(filename), runparams);
2944 else if (backend_format == "lyx")
2945 writeFile(FileName(filename));
2947 else if (isDocBook()) {
2948 runparams.nice = !put_in_tempdir;
2949 makeDocBookFile(FileName(filename), runparams);
2952 else if (backend_format == format) {
2953 runparams.nice = true;
2954 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2956 } else if (!lyxrc.tex_allows_spaces
2957 && contains(filePath(), ' ')) {
2958 Alert::error(_("File name error"),
2959 _("The directory path to the document cannot contain spaces."));
2962 runparams.nice = false;
2963 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2967 string const error_type = (format == "program")
2968 ? "Build" : bufferFormat();
2969 ErrorList & error_list = d->errorLists[error_type];
2970 string const ext = formats.extension(format);
2971 FileName const tmp_result_file(changeExtension(filename, ext));
2972 bool const success = theConverters().convert(this, FileName(filename),
2973 tmp_result_file, FileName(absFileName()), backend_format, format,
2975 // Emit the signal to show the error list.
2976 if (format != backend_format) {
2978 // also to the children, in case of master-buffer-view
2979 std::vector<Buffer *> clist = getChildren();
2980 for (vector<Buffer *>::const_iterator cit = clist.begin();
2981 cit != clist.end(); ++cit)
2982 (*cit)->errors(error_type, true);
2987 if (put_in_tempdir) {
2988 result_file = tmp_result_file.absFilename();
2992 result_file = changeExtension(exportFileName().absFilename(), ext);
2993 // We need to copy referenced files (e. g. included graphics
2994 // if format == "dvi") to the result dir.
2995 vector<ExportedFile> const files =
2996 runparams.exportdata->externalFiles(format);
2997 string const dest = onlyPath(result_file);
2998 CopyStatus status = SUCCESS;
2999 for (vector<ExportedFile>::const_iterator it = files.begin();
3000 it != files.end() && status != CANCEL; ++it) {
3001 string const fmt = formats.getFormatFromFile(it->sourceName);
3002 status = copyFile(fmt, it->sourceName,
3003 makeAbsPath(it->exportName, dest),
3004 it->exportName, status == FORCE);
3006 if (status == CANCEL) {
3007 message(_("Document export cancelled."));
3008 } else if (tmp_result_file.exists()) {
3009 // Finally copy the main file
3010 status = copyFile(format, tmp_result_file,
3011 FileName(result_file), result_file,
3013 message(bformat(_("Document exported as %1$s "
3015 formats.prettyName(format),
3016 makeDisplayPath(result_file)));
3018 // This must be a dummy converter like fax (bug 1888)
3019 message(bformat(_("Document exported as %1$s"),
3020 formats.prettyName(format)));
3027 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
3030 return doExport(format, put_in_tempdir, result_file);
3034 bool Buffer::preview(string const & format) const
3037 if (!doExport(format, true, result_file))
3039 return formats.view(*this, FileName(result_file), format);
3043 bool Buffer::isExportable(string const & format) const
3045 vector<string> backs = backends();
3046 for (vector<string>::const_iterator it = backs.begin();
3047 it != backs.end(); ++it)
3048 if (theConverters().isReachable(*it, format))
3054 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
3056 vector<string> backs = backends();
3057 vector<Format const *> result =
3058 theConverters().getReachable(backs[0], only_viewable, true);
3059 for (vector<string>::const_iterator it = backs.begin() + 1;
3060 it != backs.end(); ++it) {
3061 vector<Format const *> r =
3062 theConverters().getReachable(*it, only_viewable, false);
3063 result.insert(result.end(), r.begin(), r.end());
3069 vector<string> Buffer::backends() const
3072 if (params().baseClass()->isTeXClassAvailable()) {
3073 v.push_back(bufferFormat());
3074 // FIXME: Don't hardcode format names here, but use a flag
3075 if (v.back() == "latex")
3076 v.push_back("pdflatex");
3078 v.push_back("text");
3079 v.push_back("xhtml");
3085 bool Buffer::readFileHelper(FileName const & s)
3087 // File information about normal file
3089 docstring const file = makeDisplayPath(s.absFilename(), 50);
3090 docstring text = bformat(_("The specified document\n%1$s"
3091 "\ncould not be read."), file);
3092 Alert::error(_("Could not read document"), text);
3096 // Check if emergency save file exists and is newer.
3097 FileName const e(s.absFilename() + ".emergency");
3099 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
3100 docstring const file = makeDisplayPath(s.absFilename(), 20);
3101 docstring const text =
3102 bformat(_("An emergency save of the document "
3104 "Recover emergency save?"), file);
3105 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
3106 _("&Recover"), _("&Load Original"),
3110 // the file is not saved if we load the emergency file.
3115 if ((res = readFile(e)) == success)
3116 str = _("Document was successfully recovered.");
3118 str = _("Document was NOT successfully recovered.");
3119 str += "\n\n" + _("Remove emergency file now?");
3121 if (!Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3122 _("&Remove"), _("&Keep it"))) {
3125 Alert::warning(_("Emergency file deleted"),
3126 _("Do not forget to save your file now!"), true);
3131 if (!Alert::prompt(_("Delete emergency file?"),
3132 _("Remove emergency file now?"), 1, 1,
3133 _("&Remove"), _("&Keep it")))
3141 // Now check if autosave file is newer.
3142 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
3144 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
3145 docstring const file = makeDisplayPath(s.absFilename(), 20);
3146 docstring const text =
3147 bformat(_("The backup of the document "
3148 "%1$s is newer.\n\nLoad the "
3149 "backup instead?"), file);
3150 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
3151 _("&Load backup"), _("Load &original"),
3155 // the file is not saved if we load the autosave file.
3159 // Here we delete the autosave
3170 bool Buffer::loadLyXFile(FileName const & s)
3172 if (s.isReadableFile()) {
3173 if (readFileHelper(s)) {
3174 lyxvc().file_found_hook(s);
3175 if (!s.isWritable())
3180 docstring const file = makeDisplayPath(s.absFilename(), 20);
3181 // Here we probably should run
3182 if (LyXVC::file_not_found_hook(s)) {
3183 docstring const text =
3184 bformat(_("Do you want to retrieve the document"
3185 " %1$s from version control?"), file);
3186 int const ret = Alert::prompt(_("Retrieve from version control?"),
3187 text, 0, 1, _("&Retrieve"), _("&Cancel"));
3190 // How can we know _how_ to do the checkout?
3191 // With the current VC support it has to be,
3192 // a RCS file since CVS do not have special ,v files.
3194 return loadLyXFile(s);
3202 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3204 TeXErrors::Errors::const_iterator cit = terr.begin();
3205 TeXErrors::Errors::const_iterator end = terr.end();
3207 for (; cit != end; ++cit) {
3210 int errorRow = cit->error_in_line;
3211 bool found = d->texrow.getIdFromRow(errorRow, id_start,
3217 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
3218 } while (found && id_start == id_end && pos_start == pos_end);
3220 errorList.push_back(ErrorItem(cit->error_desc,
3221 cit->error_text, id_start, pos_start, pos_end));
3226 void Buffer::setBuffersForInsets() const
3228 inset().setBuffer(const_cast<Buffer &>(*this));
3232 void Buffer::updateLabels(UpdateScope scope) const
3234 // Use the master text class also for child documents
3235 Buffer const * const master = masterBuffer();
3236 DocumentClass const & textclass = master->params().documentClass();
3238 // keep the buffers to be children in this set. If the call from the
3239 // master comes back we can see which of them were actually seen (i.e.
3240 // via an InsetInclude). The remaining ones in the set need still be updated.
3241 static std::set<Buffer const *> bufToUpdate;
3242 if (scope == UpdateMaster) {
3243 // If this is a child document start with the master
3244 if (master != this) {
3245 bufToUpdate.insert(this);
3246 master->updateLabels();
3247 // Do this here in case the master has no gui associated with it. Then,
3248 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3252 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3253 if (bufToUpdate.find(this) == bufToUpdate.end())
3257 // start over the counters in the master
3258 textclass.counters().reset();
3261 // update will be done below for this buffer
3262 bufToUpdate.erase(this);
3264 // update all caches
3265 clearReferenceCache();
3268 Buffer & cbuf = const_cast<Buffer &>(*this);
3270 LASSERT(!text().paragraphs().empty(), /**/);
3273 ParIterator parit = cbuf.par_iterator_begin();
3274 updateLabels(parit);
3277 // TocBackend update will be done later.
3280 cbuf.tocBackend().update();
3281 if (scope == UpdateMaster)
3282 cbuf.structureChanged();
3286 static depth_type getDepth(DocIterator const & it)
3288 depth_type depth = 0;
3289 for (size_t i = 0 ; i < it.depth() ; ++i)
3290 if (!it[i].inset().inMathed())
3291 depth += it[i].paragraph().getDepth() + 1;
3292 // remove 1 since the outer inset does not count
3296 static depth_type getItemDepth(ParIterator const & it)
3298 Paragraph const & par = *it;
3299 LabelType const labeltype = par.layout().labeltype;
3301 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3304 // this will hold the lowest depth encountered up to now.
3305 depth_type min_depth = getDepth(it);
3306 ParIterator prev_it = it;
3309 --prev_it.top().pit();
3311 // start of nested inset: go to outer par
3313 if (prev_it.empty()) {
3314 // start of document: nothing to do
3319 // We search for the first paragraph with same label
3320 // that is not more deeply nested.
3321 Paragraph & prev_par = *prev_it;
3322 depth_type const prev_depth = getDepth(prev_it);
3323 if (labeltype == prev_par.layout().labeltype) {
3324 if (prev_depth < min_depth)
3325 return prev_par.itemdepth + 1;
3326 if (prev_depth == min_depth)
3327 return prev_par.itemdepth;
3329 min_depth = min(min_depth, prev_depth);
3330 // small optimization: if we are at depth 0, we won't
3331 // find anything else
3332 if (prev_depth == 0)
3338 static bool needEnumCounterReset(ParIterator const & it)
3340 Paragraph const & par = *it;
3341 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3342 depth_type const cur_depth = par.getDepth();
3343 ParIterator prev_it = it;
3344 while (prev_it.pit()) {
3345 --prev_it.top().pit();
3346 Paragraph const & prev_par = *prev_it;
3347 if (prev_par.getDepth() <= cur_depth)
3348 return prev_par.layout().labeltype != LABEL_ENUMERATE;
3350 // start of nested inset: reset
3355 // set the label of a paragraph. This includes the counters.
3356 static void setLabel(Buffer const & buf, ParIterator & it)
3358 BufferParams const & bp = buf.masterBuffer()->params();
3359 DocumentClass const & textclass = bp.documentClass();
3360 Paragraph & par = it.paragraph();
3361 Layout const & layout = par.layout();
3362 Counters & counters = textclass.counters();
3364 if (par.params().startOfAppendix()) {
3365 // FIXME: only the counter corresponding to toplevel
3366 // sectionning should be reset
3368 counters.appendix(true);
3370 par.params().appendix(counters.appendix());
3372 // Compute the item depth of the paragraph
3373 par.itemdepth = getItemDepth(it);
3375 if (layout.margintype == MARGIN_MANUAL
3376 || layout.latextype == LATEX_BIB_ENVIRONMENT) {
3377 if (par.params().labelWidthString().empty())
3378 par.params().labelWidthString(par.expandLabel(layout, bp));
3380 par.params().labelWidthString(docstring());
3383 switch(layout.labeltype) {
3385 if (layout.toclevel <= bp.secnumdepth
3386 && (layout.latextype != LATEX_ENVIRONMENT
3387 || it.text()->isFirstInSequence(it.pit()))) {
3388 counters.step(layout.counter);
3389 par.params().labelString(
3390 par.expandLabel(layout, bp));
3392 par.params().labelString(docstring());
3395 case LABEL_ITEMIZE: {
3396 // At some point of time we should do something more
3397 // clever here, like:
3398 // par.params().labelString(
3399 // bp.user_defined_bullet(par.itemdepth).getText());
3400 // for now, use a simple hardcoded label
3401 docstring itemlabel;
3402 switch (par.itemdepth) {
3404 itemlabel = char_type(0x2022);
3407 itemlabel = char_type(0x2013);
3410 itemlabel = char_type(0x2217);
3413 itemlabel = char_type(0x2219); // or 0x00b7
3416 par.params().labelString(itemlabel);
3420 case LABEL_ENUMERATE: {
3421 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
3423 switch (par.itemdepth) {
3432 enumcounter += "iv";
3435 // not a valid enumdepth...
3439 // Maybe we have to reset the enumeration counter.
3440 if (needEnumCounterReset(it))
3441 counters.reset(enumcounter);
3442 counters.step(enumcounter);
3444 string const & lang = par.getParLanguage(bp)->code();
3445 par.params().labelString(counters.theCounter(enumcounter, lang));
3450 case LABEL_SENSITIVE: {
3451 string const & type = counters.current_float();
3452 docstring full_label;
3454 full_label = buf.B_("Senseless!!! ");
3456 docstring name = buf.B_(textclass.floats().getType(type).name());
3457 if (counters.hasCounter(from_utf8(type))) {
3458 string const & lang = par.getParLanguage(bp)->code();
3459 counters.step(from_utf8(type));
3460 full_label = bformat(from_ascii("%1$s %2$s:"),
3462 counters.theCounter(from_utf8(type), lang));
3464 full_label = bformat(from_ascii("%1$s #:"), name);
3466 par.params().labelString(full_label);
3470 case LABEL_NO_LABEL:
3471 par.params().labelString(docstring());
3475 case LABEL_TOP_ENVIRONMENT:
3476 case LABEL_CENTERED_TOP_ENVIRONMENT:
3479 par.params().labelString(par.expandLabel(layout, bp));
3485 void Buffer::updateLabels(ParIterator & parit) const
3487 LASSERT(parit.pit() == 0, /**/);
3489 // set the position of the text in the buffer to be able
3490 // to resolve macros in it. This has nothing to do with
3491 // labels, but by putting it here we avoid implementing
3492 // a whole bunch of traversal routines just for this call.
3493 parit.text()->setMacrocontextPosition(parit);
3495 depth_type maxdepth = 0;
3496 pit_type const lastpit = parit.lastpit();
3497 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
3498 // reduce depth if necessary
3499 parit->params().depth(min(parit->params().depth(), maxdepth));
3500 maxdepth = parit->getMaxDepthAfter();
3502 // set the counter for this paragraph
3503 setLabel(*this, parit);
3506 InsetList::const_iterator iit = parit->insetList().begin();
3507 InsetList::const_iterator end = parit->insetList().end();
3508 for (; iit != end; ++iit) {
3509 parit.pos() = iit->pos;
3510 iit->inset->updateLabels(parit);
3516 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
3517 WordLangTuple & word_lang, docstring_list & suggestions) const
3521 suggestions.clear();
3522 word_lang = WordLangTuple();
3523 // OK, we start from here.
3524 DocIterator const end = doc_iterator_end(this);
3525 for (; from != end; from.forwardPos()) {
3526 // We are only interested in text so remove the math CursorSlice.
3527 while (from.inMathed())
3528 from.forwardInset();
3530 if (from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions)) {