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"
48 #include "output_docbook.h"
50 #include "output_latex.h"
51 #include "output_xhtml.h"
52 #include "output_plaintext.h"
53 #include "Paragraph.h"
54 #include "ParagraphParameters.h"
55 #include "ParIterator.h"
56 #include "PDFOptions.h"
57 #include "SpellChecker.h"
60 #include "TexStream.h"
62 #include "TextClass.h"
63 #include "TocBackend.h"
65 #include "VCBackend.h"
67 #include "WordLangTuple.h"
70 #include "insets/InsetBibitem.h"
71 #include "insets/InsetBibtex.h"
72 #include "insets/InsetBranch.h"
73 #include "insets/InsetInclude.h"
74 #include "insets/InsetText.h"
76 #include "mathed/MacroTable.h"
77 #include "mathed/MathMacroTemplate.h"
78 #include "mathed/MathSupport.h"
80 #include "frontends/alert.h"
81 #include "frontends/Delegates.h"
82 #include "frontends/WorkAreaManager.h"
84 #include "graphics/Previews.h"
86 #include "support/lassert.h"
87 #include "support/convert.h"
88 #include "support/debug.h"
89 #include "support/docstring_list.h"
90 #include "support/ExceptionMessage.h"
91 #include "support/FileName.h"
92 #include "support/FileNameList.h"
93 #include "support/filetools.h"
94 #include "support/ForkedCalls.h"
95 #include "support/gettext.h"
96 #include "support/gzstream.h"
97 #include "support/lstrings.h"
98 #include "support/lyxalgo.h"
99 #include "support/os.h"
100 #include "support/Package.h"
101 #include "support/Path.h"
102 #include "support/Systemcall.h"
103 #include "support/textutils.h"
104 #include "support/types.h"
106 #include <boost/bind.hpp>
107 #include <boost/shared_ptr.hpp>
119 using namespace lyx::support;
123 namespace Alert = frontend::Alert;
124 namespace os = support::os;
128 // Do not remove the comment below, so we get merge conflict in
129 // independent branches. Instead add your own.
130 int const LYX_FORMAT = 375; // jspitzm: includeonly support
132 typedef map<string, bool> DepClean;
133 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
135 void showPrintError(string const & name)
137 docstring str = bformat(_("Could not print the document %1$s.\n"
138 "Check that your printer is set up correctly."),
139 makeDisplayPath(name, 50));
140 Alert::error(_("Print document failed"), str);
145 class BufferSet : public std::set<Buffer const *> {};
150 Impl(Buffer & parent, FileName const & file, bool readonly, Buffer const * cloned_buffer);
164 mutable TexRow texrow;
166 /// need to regenerate .tex?
170 mutable bool lyx_clean;
172 /// is autosave needed?
173 mutable bool bak_clean;
175 /// is this a unnamed file (New...)?
181 /// name of the file the buffer is associated with.
184 /** Set to true only when the file is fully loaded.
185 * Used to prevent the premature generation of previews
186 * and by the citation inset.
188 bool file_fully_loaded;
191 mutable TocBackend toc_backend;
194 typedef pair<DocIterator, MacroData> ScopeMacro;
195 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
196 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
197 /// map from the macro name to the position map,
198 /// which maps the macro definition position to the scope and the MacroData.
199 NamePositionScopeMacroMap macros;
202 /// positions of child buffers in the buffer
203 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
204 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
205 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
206 /// position of children buffers in this buffer
207 BufferPositionMap children_positions;
208 /// map from children inclusion positions to their scope and their buffer
209 PositionScopeBufferMap position_to_children;
211 /// Container for all sort of Buffer dependant errors.
212 map<string, ErrorList> errorLists;
214 /// timestamp and checksum used to test if the file has been externally
215 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
217 unsigned long checksum_;
220 frontend::WorkAreaManager * wa_;
225 /// A cache for the bibfiles (including bibfiles of loaded child
226 /// documents), needed for appropriate update of natbib labels.
227 mutable support::FileNameList bibfilesCache_;
229 // FIXME The caching mechanism could be improved. At present, we have a
230 // cache for each Buffer, that caches all the bibliography info for that
231 // Buffer. A more efficient solution would be to have a global cache per
232 // file, and then to construct the Buffer's bibinfo from that.
233 /// A cache for bibliography info
234 mutable BiblioInfo bibinfo_;
235 /// whether the bibinfo cache is valid
236 bool bibinfoCacheValid_;
237 /// Cache of timestamps of .bib files
238 map<FileName, time_t> bibfileStatus_;
240 mutable RefCache ref_cache_;
242 /// our Text that should be wrapped in an InsetText
245 /// This is here to force the test to be done whenever parent_buffer
247 Buffer const * parent() const {
248 // if parent_buffer is not loaded, then it has been unloaded,
249 // which means that parent_buffer is an invalid pointer. So we
250 // set it to null in that case.
251 if (!theBufferList().isLoaded(parent_buffer))
253 return parent_buffer;
256 void setParent(Buffer const * pb) {
257 if (parent_buffer && pb && parent_buffer != pb)
258 LYXERR0("Warning: a buffer should not have two parents!");
262 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
263 /// This one is useful for preview detached in a thread.
264 Buffer const * cloned_buffer_;
267 /// So we can force access via the accessors.
268 mutable Buffer const * parent_buffer;
273 /// Creates the per buffer temporary directory
274 static FileName createBufferTmpDir()
277 // We are in our own directory. Why bother to mangle name?
278 // In fact I wrote this code to circumvent a problematic behaviour
279 // (bug?) of EMX mkstemp().
280 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
281 convert<string>(count++));
283 if (!tmpfl.createDirectory(0777)) {
284 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
285 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
286 from_utf8(tmpfl.absFilename())));
292 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_,
293 Buffer const * cloned_buffer)
294 : lyx_clean(true), bak_clean(true), unnamed(false),
295 read_only(readonly_), filename(file), file_fully_loaded(false),
296 toc_backend(&parent), macro_lock(false), timestamp_(0),
297 checksum_(0), wa_(0), undo_(parent), bibinfoCacheValid_(false),
298 cloned_buffer_(cloned_buffer), parent_buffer(0)
300 if (!cloned_buffer_) {
301 temppath = createBufferTmpDir();
302 lyxvc.setBuffer(&parent);
304 wa_ = new frontend::WorkAreaManager;
307 temppath = cloned_buffer_->d->temppath;
308 file_fully_loaded = true;
309 params = cloned_buffer_->d->params;
313 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
314 : d(new Impl(*this, FileName(file), readonly, cloned_buffer)), gui_(0)
316 LYXERR(Debug::INFO, "Buffer::Buffer()");
318 d->inset = new InsetText(*cloned_buffer->d->inset);
319 d->inset->setBuffer(*this);
320 // FIXME: optimize this loop somewhat, maybe by creating a new
321 // general recursive Inset::setId().
322 DocIterator it = doc_iterator_begin(this);
323 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
324 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
325 it.paragraph().setId(cloned_it.paragraph().id());
327 d->inset = new InsetText(this);
328 d->inset->setAutoBreakRows(true);
329 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
335 LYXERR(Debug::INFO, "Buffer::~Buffer()");
336 // here the buffer should take care that it is
337 // saved properly, before it goes into the void.
339 // GuiView already destroyed
343 // No need to do additional cleanups for internal buffer.
348 // loop over children
349 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
350 Impl::BufferPositionMap::iterator end = d->children_positions.end();
351 for (; it != end; ++it) {
352 Buffer * child = const_cast<Buffer *>(it->first);
353 // The child buffer might have been closed already.
354 if (theBufferList().isLoaded(child))
355 theBufferList().releaseChild(this, child);
359 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
360 msg += emergencyWrite();
361 Alert::warning(_("Attempting to close changed document!"), msg);
364 // clear references to children in macro tables
365 d->children_positions.clear();
366 d->position_to_children.clear();
368 if (!d->cloned_buffer_ && !d->temppath.destroyDirectory()) {
369 Alert::warning(_("Could not remove temporary directory"),
370 bformat(_("Could not remove the temporary directory %1$s"),
371 from_utf8(d->temppath.absFilename())));
374 // Remove any previewed LaTeX snippets associated with this buffer.
375 thePreviews().removeLoader(*this);
381 Buffer * Buffer::clone() const
383 // FIXME for asynchronous export and preview: We must also clone all
384 // the child buffers!
385 return new Buffer(fileName().absFilename(), false, this);
389 bool Buffer::isClone() const
391 return d->cloned_buffer_;
395 void Buffer::changed() const
402 frontend::WorkAreaManager & Buffer::workAreaManager() const
404 LASSERT(d->wa_, /**/);
409 Text & Buffer::text() const
411 return d->inset->text();
415 Inset & Buffer::inset() const
421 BufferParams & Buffer::params()
427 BufferParams const & Buffer::params() const
433 ParagraphList & Buffer::paragraphs()
435 return text().paragraphs();
439 ParagraphList const & Buffer::paragraphs() const
441 return text().paragraphs();
445 LyXVC & Buffer::lyxvc()
451 LyXVC const & Buffer::lyxvc() const
457 string const Buffer::temppath() const
459 return d->temppath.absFilename();
463 TexRow & Buffer::texrow()
469 TexRow const & Buffer::texrow() const
475 TocBackend & Buffer::tocBackend() const
477 return d->toc_backend;
481 Undo & Buffer::undo()
487 string Buffer::latexName(bool const no_path) const
489 FileName latex_name =
490 makeLatexName(exportFileName());
491 return no_path ? latex_name.onlyFileName()
492 : latex_name.absFilename();
496 FileName Buffer::exportFileName() const
498 docstring const branch_suffix =
499 params().branchlist().getFilenameSuffix();
500 if (branch_suffix.empty())
503 string const name = fileName().onlyFileNameWithoutExt()
504 + to_utf8(branch_suffix);
505 FileName res(fileName().onlyPath().absFilename() + "/" + name);
506 res.changeExtension(fileName().extension());
512 string Buffer::logName(LogType * type) const
514 string const filename = latexName(false);
516 if (filename.empty()) {
522 string const path = temppath();
524 FileName const fname(addName(temppath(),
525 onlyFilename(changeExtension(filename,
528 // FIXME: how do we know this is the name of the build log?
529 FileName const bname(
530 addName(path, onlyFilename(
531 changeExtension(filename,
532 formats.extension(bufferFormat()) + ".out"))));
534 // Also consider the master buffer log file
535 FileName masterfname = fname;
537 if (masterBuffer() != this) {
538 string const mlogfile = masterBuffer()->logName(&mtype);
539 masterfname = FileName(mlogfile);
542 // If no Latex log or Build log is newer, show Build log
543 if (bname.exists() &&
544 ((!fname.exists() && !masterfname.exists())
545 || (fname.lastModified() < bname.lastModified()
546 && masterfname.lastModified() < bname.lastModified()))) {
547 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
550 return bname.absFilename();
551 // If we have a newer master file log or only a master log, show this
552 } else if (fname != masterfname
553 && (!fname.exists() && (masterfname.exists()
554 || fname.lastModified() < masterfname.lastModified()))) {
555 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
558 return masterfname.absFilename();
560 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
563 return fname.absFilename();
567 void Buffer::setReadonly(bool const flag)
569 if (d->read_only != flag) {
576 void Buffer::setFileName(string const & newfile)
578 d->filename = makeAbsPath(newfile);
579 setReadonly(d->filename.isReadOnly());
584 int Buffer::readHeader(Lexer & lex)
586 int unknown_tokens = 0;
588 int begin_header_line = -1;
590 // Initialize parameters that may be/go lacking in header:
591 params().branchlist().clear();
592 params().preamble.erase();
593 params().options.erase();
594 params().master.erase();
595 params().float_placement.erase();
596 params().paperwidth.erase();
597 params().paperheight.erase();
598 params().leftmargin.erase();
599 params().rightmargin.erase();
600 params().topmargin.erase();
601 params().bottommargin.erase();
602 params().headheight.erase();
603 params().headsep.erase();
604 params().footskip.erase();
605 params().columnsep.erase();
606 params().fontsCJK.erase();
607 params().listings_params.clear();
608 params().clearLayoutModules();
609 params().clearRemovedModules();
610 params().clearIncludedChildren();
611 params().pdfoptions().clear();
612 params().indiceslist().clear();
613 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
615 for (int i = 0; i < 4; ++i) {
616 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
617 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
620 ErrorList & errorList = d->errorLists["Parse"];
629 if (token == "\\end_header")
633 if (token == "\\begin_header") {
634 begin_header_line = line;
638 LYXERR(Debug::PARSER, "Handling document header token: `"
641 string unknown = params().readToken(lex, token, d->filename.onlyPath());
642 if (!unknown.empty()) {
643 if (unknown[0] != '\\' && token == "\\textclass") {
644 Alert::warning(_("Unknown document class"),
645 bformat(_("Using the default document class, because the "
646 "class %1$s is unknown."), from_utf8(unknown)));
649 docstring const s = bformat(_("Unknown token: "
653 errorList.push_back(ErrorItem(_("Document header error"),
658 if (begin_header_line) {
659 docstring const s = _("\\begin_header is missing");
660 errorList.push_back(ErrorItem(_("Document header error"),
664 params().makeDocumentClass();
666 return unknown_tokens;
671 // changed to be public and have one parameter
672 // Returns true if "\end_document" is not read (Asger)
673 bool Buffer::readDocument(Lexer & lex)
675 ErrorList & errorList = d->errorLists["Parse"];
678 if (!lex.checkFor("\\begin_document")) {
679 docstring const s = _("\\begin_document is missing");
680 errorList.push_back(ErrorItem(_("Document header error"),
684 // we are reading in a brand new document
685 LASSERT(paragraphs().empty(), /**/);
689 if (params().outputChanges) {
690 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
691 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
692 LaTeXFeatures::isAvailable("xcolor");
694 if (!dvipost && !xcolorulem) {
695 Alert::warning(_("Changes not shown in LaTeX output"),
696 _("Changes will not be highlighted in LaTeX output, "
697 "because neither dvipost nor xcolor/ulem are installed.\n"
698 "Please install these packages or redefine "
699 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
700 } else if (!xcolorulem) {
701 Alert::warning(_("Changes not shown in LaTeX output"),
702 _("Changes will not be highlighted in LaTeX output "
703 "when using pdflatex, because xcolor and ulem are not installed.\n"
704 "Please install both packages or redefine "
705 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
709 if (!params().master.empty()) {
710 FileName const master_file = makeAbsPath(params().master,
711 onlyPath(absFileName()));
712 if (isLyXFilename(master_file.absFilename())) {
714 checkAndLoadLyXFile(master_file, true);
716 // necessary e.g. after a reload
717 // to re-register the child (bug 5873)
718 // FIXME: clean up updateMacros (here, only
719 // child registering is needed).
720 master->updateMacros();
721 // set master as master buffer, but only
722 // if we are a real child
723 if (master->isChild(this))
725 // if the master is not fully loaded
726 // it is probably just loading this
727 // child. No warning needed then.
728 else if (master->isFullyLoaded())
729 LYXERR0("The master '"
731 << "' assigned to this document ("
733 << ") does not include "
734 "this document. Ignoring the master assignment.");
739 // assure we have a default index
740 params().indiceslist().addDefault(B_("Index"));
743 bool const res = text().read(lex, errorList, d->inset);
747 updateMacroInstances();
752 bool Buffer::readString(string const & s)
754 params().compressed = false;
756 // remove dummy empty par
757 paragraphs().clear();
761 FileName const name = FileName::tempName("Buffer_readString");
762 switch (readFile(lex, name, true)) {
766 // We need to call lyx2lyx, so write the input to a file
767 ofstream os(name.toFilesystemEncoding().c_str());
770 return readFile(name);
780 bool Buffer::readFile(FileName const & filename)
782 FileName fname(filename);
784 params().compressed = fname.isZippedFile();
786 // remove dummy empty par
787 paragraphs().clear();
790 if (readFile(lex, fname) != success)
797 bool Buffer::isFullyLoaded() const
799 return d->file_fully_loaded;
803 void Buffer::setFullyLoaded(bool value)
805 d->file_fully_loaded = value;
809 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
812 LASSERT(!filename.empty(), /**/);
814 // the first (non-comment) token _must_ be...
815 if (!lex.checkFor("\\lyxformat")) {
816 Alert::error(_("Document format failure"),
817 bformat(_("%1$s is not a readable LyX document."),
818 from_utf8(filename.absFilename())));
824 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
825 // if present remove ".," from string.
826 size_t dot = tmp_format.find_first_of(".,");
827 //lyxerr << " dot found at " << dot << endl;
828 if (dot != string::npos)
829 tmp_format.erase(dot, 1);
830 int const file_format = convert<int>(tmp_format);
831 //lyxerr << "format: " << file_format << endl;
833 // save timestamp and checksum of the original disk file, making sure
834 // to not overwrite them with those of the file created in the tempdir
835 // when it has to be converted to the current format.
837 // Save the timestamp and checksum of disk file. If filename is an
838 // emergency file, save the timestamp and checksum of the original lyx file
839 // because isExternallyModified will check for this file. (BUG4193)
840 string diskfile = filename.absFilename();
841 if (suffixIs(diskfile, ".emergency"))
842 diskfile = diskfile.substr(0, diskfile.size() - 10);
843 saveCheckSum(FileName(diskfile));
846 if (file_format != LYX_FORMAT) {
849 // lyx2lyx would fail
852 FileName const tmpfile = FileName::tempName("Buffer_readFile");
853 if (tmpfile.empty()) {
854 Alert::error(_("Conversion failed"),
855 bformat(_("%1$s is from a different"
856 " version of LyX, but a temporary"
857 " file for converting it could"
859 from_utf8(filename.absFilename())));
862 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
863 if (lyx2lyx.empty()) {
864 Alert::error(_("Conversion script not found"),
865 bformat(_("%1$s is from a different"
866 " version of LyX, but the"
867 " conversion script lyx2lyx"
868 " could not be found."),
869 from_utf8(filename.absFilename())));
872 ostringstream command;
873 command << os::python()
874 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
875 << " -t " << convert<string>(LYX_FORMAT)
876 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
877 << ' ' << quoteName(filename.toFilesystemEncoding());
878 string const command_str = command.str();
880 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
882 cmd_ret const ret = runCommand(command_str);
883 if (ret.first != 0) {
884 Alert::error(_("Conversion script failed"),
885 bformat(_("%1$s is from a different version"
886 " of LyX, but the lyx2lyx script"
887 " failed to convert it."),
888 from_utf8(filename.absFilename())));
891 bool const ret = readFile(tmpfile);
892 // Do stuff with tmpfile name and buffer name here.
893 return ret ? success : failure;
898 if (readDocument(lex)) {
899 Alert::error(_("Document format failure"),
900 bformat(_("%1$s ended unexpectedly, which means"
901 " that it is probably corrupted."),
902 from_utf8(filename.absFilename())));
905 d->file_fully_loaded = true;
910 // Should probably be moved to somewhere else: BufferView? LyXView?
911 bool Buffer::save() const
913 // We don't need autosaves in the immediate future. (Asger)
914 resetAutosaveTimers();
916 string const encodedFilename = d->filename.toFilesystemEncoding();
919 bool madeBackup = false;
921 // make a backup if the file already exists
922 if (lyxrc.make_backup && fileName().exists()) {
923 backupName = FileName(absFileName() + '~');
924 if (!lyxrc.backupdir_path.empty()) {
925 string const mangledName =
926 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
927 backupName = FileName(addName(lyxrc.backupdir_path,
930 if (fileName().copyTo(backupName)) {
933 Alert::error(_("Backup failure"),
934 bformat(_("Cannot create backup file %1$s.\n"
935 "Please check whether the directory exists and is writeable."),
936 from_utf8(backupName.absFilename())));
937 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
941 // ask if the disk file has been externally modified (use checksum method)
942 if (fileName().exists() && isExternallyModified(checksum_method)) {
943 docstring const file = makeDisplayPath(absFileName(), 20);
944 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
945 "you want to overwrite this file?"), file);
946 int const ret = Alert::prompt(_("Overwrite modified file?"),
947 text, 1, 1, _("&Overwrite"), _("&Cancel"));
952 if (writeFile(d->filename)) {
956 // Saving failed, so backup is not backup
958 backupName.moveTo(d->filename);
964 bool Buffer::writeFile(FileName const & fname) const
966 if (d->read_only && fname == d->filename)
971 docstring const str = bformat(_("Saving document %1$s..."),
972 makeDisplayPath(fname.absFilename()));
975 if (params().compressed) {
976 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
977 retval = ofs && write(ofs);
979 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
980 retval = ofs && write(ofs);
984 message(str + _(" could not write file!"));
988 removeAutosaveFile();
990 saveCheckSum(d->filename);
991 message(str + _(" done."));
997 docstring Buffer::emergencyWrite()
999 // No need to save if the buffer has not changed.
1003 string const doc = isUnnamed() ? onlyFilename(absFileName()) : absFileName();
1005 docstring user_message = bformat(
1006 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1008 // We try to save three places:
1009 // 1) Same place as document. Unless it is an unnamed doc.
1011 string s = absFileName();
1014 if (writeFile(FileName(s))) {
1016 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1017 return user_message;
1019 user_message += _(" Save failed! Trying again...\n");
1023 // 2) In HOME directory.
1024 string s = addName(package().home_dir().absFilename(), absFileName());
1026 lyxerr << ' ' << s << endl;
1027 if (writeFile(FileName(s))) {
1029 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1030 return user_message;
1033 user_message += _(" Save failed! Trying yet again...\n");
1035 // 3) In "/tmp" directory.
1036 // MakeAbsPath to prepend the current
1037 // drive letter on OS/2
1038 s = addName(package().temp_dir().absFilename(), absFileName());
1040 lyxerr << ' ' << s << endl;
1041 if (writeFile(FileName(s))) {
1043 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1044 return user_message;
1047 user_message += _(" Save failed! Bummer. Document is lost.");
1050 return user_message;
1054 bool Buffer::write(ostream & ofs) const
1057 // Use the standard "C" locale for file output.
1058 ofs.imbue(locale::classic());
1061 // The top of the file should not be written by params().
1063 // write out a comment in the top of the file
1064 ofs << "#LyX " << lyx_version
1065 << " created this file. For more info see http://www.lyx.org/\n"
1066 << "\\lyxformat " << LYX_FORMAT << "\n"
1067 << "\\begin_document\n";
1069 /// For each author, set 'used' to true if there is a change
1070 /// by this author in the document; otherwise set it to 'false'.
1071 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1072 AuthorList::Authors::const_iterator a_end = params().authors().end();
1073 for (; a_it != a_end; ++a_it)
1074 a_it->setUsed(false);
1076 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1077 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1078 for ( ; it != end; ++it)
1079 it->checkAuthors(params().authors());
1081 // now write out the buffer parameters.
1082 ofs << "\\begin_header\n";
1083 params().writeFile(ofs);
1084 ofs << "\\end_header\n";
1087 ofs << "\n\\begin_body\n";
1089 ofs << "\n\\end_body\n";
1091 // Write marker that shows file is complete
1092 ofs << "\\end_document" << endl;
1094 // Shouldn't really be needed....
1097 // how to check if close went ok?
1098 // Following is an attempt... (BE 20001011)
1100 // good() returns false if any error occured, including some
1101 // formatting error.
1102 // bad() returns true if something bad happened in the buffer,
1103 // which should include file system full errors.
1108 lyxerr << "File was not closed properly." << endl;
1115 bool Buffer::makeLaTeXFile(FileName const & fname,
1116 string const & original_path,
1117 OutputParams const & runparams_in,
1118 bool output_preamble, bool output_body) const
1120 OutputParams runparams = runparams_in;
1121 if (params().useXetex)
1122 runparams.flavor = OutputParams::XETEX;
1124 string const encoding = runparams.encoding->iconvName();
1125 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1128 try { ofs.reset(encoding); }
1129 catch (iconv_codecvt_facet_exception & e) {
1130 lyxerr << "Caught iconv exception: " << e.what() << endl;
1131 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1132 "verify that the support software for your encoding (%1$s) is "
1133 "properly installed"), from_ascii(encoding)));
1136 if (!openFileWrite(ofs, fname))
1139 //TexStream ts(ofs.rdbuf(), &texrow());
1140 ErrorList & errorList = d->errorLists["Export"];
1142 bool failed_export = false;
1145 writeLaTeXSource(ofs, original_path,
1146 runparams, output_preamble, output_body);
1148 catch (EncodingException & e) {
1149 odocstringstream ods;
1150 ods.put(e.failed_char);
1152 oss << "0x" << hex << e.failed_char << dec;
1153 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1154 " (code point %2$s)"),
1155 ods.str(), from_utf8(oss.str()));
1156 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1157 "representable in the chosen encoding.\n"
1158 "Changing the document encoding to utf8 could help."),
1159 e.par_id, e.pos, e.pos + 1));
1160 failed_export = true;
1162 catch (iconv_codecvt_facet_exception & e) {
1163 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1164 _(e.what()), -1, 0, 0));
1165 failed_export = true;
1167 catch (exception const & e) {
1168 errorList.push_back(ErrorItem(_("conversion failed"),
1169 _(e.what()), -1, 0, 0));
1170 failed_export = true;
1173 lyxerr << "Caught some really weird exception..." << endl;
1179 failed_export = true;
1180 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1184 return !failed_export;
1188 void Buffer::writeLaTeXSource(odocstream & os,
1189 string const & original_path,
1190 OutputParams const & runparams_in,
1191 bool const output_preamble, bool const output_body) const
1193 // The child documents, if any, shall be already loaded at this point.
1195 OutputParams runparams = runparams_in;
1197 // Classify the unicode characters appearing in math insets
1198 Encodings::initUnicodeMath(*this);
1200 // validate the buffer.
1201 LYXERR(Debug::LATEX, " Validating buffer...");
1202 LaTeXFeatures features(*this, params(), runparams);
1204 LYXERR(Debug::LATEX, " Buffer validation done.");
1206 // The starting paragraph of the coming rows is the
1207 // first paragraph of the document. (Asger)
1208 if (output_preamble && runparams.nice) {
1209 os << "%% LyX " << lyx_version << " created this file. "
1210 "For more info, see http://www.lyx.org/.\n"
1211 "%% Do not edit unless you really know what "
1213 d->texrow.newline();
1214 d->texrow.newline();
1216 LYXERR(Debug::INFO, "lyx document header finished");
1218 // Don't move this behind the parent_buffer=0 code below,
1219 // because then the macros will not get the right "redefinition"
1220 // flag as they don't see the parent macros which are output before.
1223 // fold macros if possible, still with parent buffer as the
1224 // macros will be put in the prefix anyway.
1225 updateMacroInstances();
1227 // There are a few differences between nice LaTeX and usual files:
1228 // usual is \batchmode and has a
1229 // special input@path to allow the including of figures
1230 // with either \input or \includegraphics (what figinsets do).
1231 // input@path is set when the actual parameter
1232 // original_path is set. This is done for usual tex-file, but not
1233 // for nice-latex-file. (Matthias 250696)
1234 // Note that input@path is only needed for something the user does
1235 // in the preamble, included .tex files or ERT, files included by
1236 // LyX work without it.
1237 if (output_preamble) {
1238 if (!runparams.nice) {
1239 // code for usual, NOT nice-latex-file
1240 os << "\\batchmode\n"; // changed
1241 // from \nonstopmode
1242 d->texrow.newline();
1244 if (!original_path.empty()) {
1246 // We don't know the encoding of inputpath
1247 docstring const inputpath = from_utf8(latex_path(original_path));
1248 os << "\\makeatletter\n"
1249 << "\\def\\input@path{{"
1250 << inputpath << "/}}\n"
1251 << "\\makeatother\n";
1252 d->texrow.newline();
1253 d->texrow.newline();
1254 d->texrow.newline();
1257 // get parent macros (if this buffer has a parent) which will be
1258 // written at the document begin further down.
1259 MacroSet parentMacros;
1260 listParentMacros(parentMacros, features);
1262 // Write the preamble
1263 runparams.use_babel = params().writeLaTeX(os, features,
1265 d->filename.onlyPath());
1267 runparams.use_japanese = features.isRequired("japanese");
1273 os << "\\begin{document}\n";
1274 d->texrow.newline();
1276 // output the parent macros
1277 MacroSet::iterator it = parentMacros.begin();
1278 MacroSet::iterator end = parentMacros.end();
1279 for (; it != end; ++it)
1280 (*it)->write(os, true);
1281 } // output_preamble
1283 d->texrow.start(paragraphs().begin()->id(), 0);
1285 LYXERR(Debug::INFO, "preamble finished, now the body.");
1287 // if we are doing a real file with body, even if this is the
1288 // child of some other buffer, let's cut the link here.
1289 // This happens for example if only a child document is printed.
1290 Buffer const * save_parent = 0;
1291 if (output_preamble) {
1292 save_parent = d->parent();
1297 latexParagraphs(*this, text(), os, d->texrow, runparams);
1299 // Restore the parenthood if needed
1300 if (output_preamble)
1301 d->setParent(save_parent);
1303 // add this just in case after all the paragraphs
1305 d->texrow.newline();
1307 if (output_preamble) {
1308 os << "\\end{document}\n";
1309 d->texrow.newline();
1310 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1312 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1314 runparams_in.encoding = runparams.encoding;
1316 // Just to be sure. (Asger)
1317 d->texrow.newline();
1319 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1320 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1324 bool Buffer::isLatex() const
1326 return params().documentClass().outputType() == LATEX;
1330 bool Buffer::isLiterate() const
1332 return params().documentClass().outputType() == LITERATE;
1336 bool Buffer::isDocBook() const
1338 return params().documentClass().outputType() == DOCBOOK;
1342 void Buffer::makeDocBookFile(FileName const & fname,
1343 OutputParams const & runparams,
1344 bool const body_only) const
1346 LYXERR(Debug::LATEX, "makeDocBookFile...");
1349 if (!openFileWrite(ofs, fname))
1352 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1356 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1360 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1361 OutputParams const & runparams,
1362 bool const only_body) const
1364 LaTeXFeatures features(*this, params(), runparams);
1369 DocumentClass const & tclass = params().documentClass();
1370 string const top_element = tclass.latexname();
1373 if (runparams.flavor == OutputParams::XML)
1374 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1377 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1380 if (! tclass.class_header().empty())
1381 os << from_ascii(tclass.class_header());
1382 else if (runparams.flavor == OutputParams::XML)
1383 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1384 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1386 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1388 docstring preamble = from_utf8(params().preamble);
1389 if (runparams.flavor != OutputParams::XML ) {
1390 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1391 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1392 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1393 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1396 string const name = runparams.nice
1397 ? changeExtension(absFileName(), ".sgml") : fname;
1398 preamble += features.getIncludedFiles(name);
1399 preamble += features.getLyXSGMLEntities();
1401 if (!preamble.empty()) {
1402 os << "\n [ " << preamble << " ]";
1407 string top = top_element;
1409 if (runparams.flavor == OutputParams::XML)
1410 top += params().language->code();
1412 top += params().language->code().substr(0, 2);
1415 if (!params().options.empty()) {
1417 top += params().options;
1420 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1421 << " file was created by LyX " << lyx_version
1422 << "\n See http://www.lyx.org/ for more information -->\n";
1424 params().documentClass().counters().reset();
1428 sgml::openTag(os, top);
1430 docbookParagraphs(text(), *this, os, runparams);
1431 sgml::closeTag(os, top_element);
1435 void Buffer::makeLyXHTMLFile(FileName const & fname,
1436 OutputParams const & runparams,
1437 bool const body_only) const
1439 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1442 if (!openFileWrite(ofs, fname))
1445 writeLyXHTMLSource(ofs, runparams, body_only);
1449 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1453 void Buffer::writeLyXHTMLSource(odocstream & os,
1454 OutputParams const & runparams,
1455 bool const only_body) const
1457 LaTeXFeatures features(*this, params(), runparams);
1459 updateLabels(UpdateMaster, true);
1464 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1465 os << "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1 plus MathML 2.0//EN\" \"http://www.w3.org/TR/MathML2/dtd/xhtml-math11-f.dtd\">\n";
1466 // FIXME Language should be set properly.
1467 os << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n";
1470 // FIXME Presumably need to set this right
1471 os << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1472 // FIXME Get this during validation? What about other meta-data?
1473 os << "<title>TBA</title>\n";
1475 os << "\n<!-- Text Class Preamble -->\n"
1476 << features.getTClassHTMLPreamble()
1477 << "\n<!-- Premable Snippets -->\n"
1478 << from_utf8(features.getPreambleSnippets());
1480 os << "\n<!-- Layout-provided Styles -->\n";
1481 docstring const styleinfo = features.getTClassHTMLStyles();
1482 if (!styleinfo.empty()) {
1483 os << "<style type='text/css'>\n"
1487 os << "</head>\n<body>\n";
1491 params().documentClass().counters().reset();
1492 xhtmlParagraphs(text(), *this, xs, runparams);
1494 os << "</body>\n</html>\n";
1498 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1499 // Other flags: -wall -v0 -x
1500 int Buffer::runChktex()
1504 // get LaTeX-Filename
1505 FileName const path(temppath());
1506 string const name = addName(path.absFilename(), latexName());
1507 string const org_path = filePath();
1509 PathChanger p(path); // path to LaTeX file
1510 message(_("Running chktex..."));
1512 // Generate the LaTeX file if neccessary
1513 OutputParams runparams(¶ms().encoding());
1514 runparams.flavor = OutputParams::LATEX;
1515 runparams.nice = false;
1516 makeLaTeXFile(FileName(name), org_path, runparams);
1519 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1520 int const res = chktex.run(terr); // run chktex
1523 Alert::error(_("chktex failure"),
1524 _("Could not run chktex successfully."));
1525 } else if (res > 0) {
1526 ErrorList & errlist = d->errorLists["ChkTeX"];
1528 bufferErrors(terr, errlist);
1539 void Buffer::validate(LaTeXFeatures & features) const
1541 params().validate(features);
1545 for_each(paragraphs().begin(), paragraphs().end(),
1546 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1548 if (lyxerr.debugging(Debug::LATEX)) {
1549 features.showStruct();
1554 void Buffer::getLabelList(vector<docstring> & list) const
1556 // If this is a child document, use the parent's list instead.
1557 Buffer const * const pbuf = d->parent();
1559 pbuf->getLabelList(list);
1564 Toc & toc = d->toc_backend.toc("label");
1565 TocIterator toc_it = toc.begin();
1566 TocIterator end = toc.end();
1567 for (; toc_it != end; ++toc_it) {
1568 if (toc_it->depth() == 0)
1569 list.push_back(toc_it->str());
1574 void Buffer::updateBibfilesCache(UpdateScope scope) const
1576 // If this is a child document, use the parent's cache instead.
1577 Buffer const * const pbuf = d->parent();
1578 if (pbuf && scope != UpdateChildOnly) {
1579 pbuf->updateBibfilesCache();
1583 d->bibfilesCache_.clear();
1584 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1585 if (it->lyxCode() == BIBTEX_CODE) {
1586 InsetBibtex const & inset =
1587 static_cast<InsetBibtex const &>(*it);
1588 support::FileNameList const bibfiles = inset.getBibFiles();
1589 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1592 } else if (it->lyxCode() == INCLUDE_CODE) {
1593 InsetInclude & inset =
1594 static_cast<InsetInclude &>(*it);
1595 inset.updateBibfilesCache();
1596 support::FileNameList const & bibfiles =
1597 inset.getBibfilesCache();
1598 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1603 // the bibinfo cache is now invalid
1604 d->bibinfoCacheValid_ = false;
1608 void Buffer::invalidateBibinfoCache()
1610 d->bibinfoCacheValid_ = false;
1614 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1616 // If this is a child document, use the parent's cache instead.
1617 Buffer const * const pbuf = d->parent();
1618 if (pbuf && scope != UpdateChildOnly)
1619 return pbuf->getBibfilesCache();
1621 // We update the cache when first used instead of at loading time.
1622 if (d->bibfilesCache_.empty())
1623 const_cast<Buffer *>(this)->updateBibfilesCache(scope);
1625 return d->bibfilesCache_;
1629 BiblioInfo const & Buffer::masterBibInfo() const
1631 // if this is a child document and the parent is already loaded
1632 // use the parent's list instead [ale990412]
1633 Buffer const * const tmp = masterBuffer();
1636 return tmp->masterBibInfo();
1637 return localBibInfo();
1641 BiblioInfo const & Buffer::localBibInfo() const
1643 if (d->bibinfoCacheValid_) {
1644 support::FileNameList const & bibfilesCache = getBibfilesCache();
1645 // compare the cached timestamps with the actual ones.
1646 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1647 support::FileNameList::const_iterator en = bibfilesCache.end();
1648 for (; ei != en; ++ ei) {
1649 time_t lastw = ei->lastModified();
1650 if (lastw != d->bibfileStatus_[*ei]) {
1651 d->bibinfoCacheValid_ = false;
1652 d->bibfileStatus_[*ei] = lastw;
1658 if (!d->bibinfoCacheValid_) {
1659 d->bibinfo_.clear();
1660 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1661 it->fillWithBibKeys(d->bibinfo_, it);
1662 d->bibinfoCacheValid_ = true;
1668 bool Buffer::isDepClean(string const & name) const
1670 DepClean::const_iterator const it = d->dep_clean.find(name);
1671 if (it == d->dep_clean.end())
1677 void Buffer::markDepClean(string const & name)
1679 d->dep_clean[name] = true;
1683 bool Buffer::isExportableFormat(string const & format) const
1685 typedef vector<Format const *> Formats;
1687 formats = exportableFormats(true);
1688 Formats::const_iterator fit = formats.begin();
1689 Formats::const_iterator end = formats.end();
1690 for (; fit != end ; ++fit) {
1691 if ((*fit)->name() == format)
1698 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1701 // FIXME? if there is an Buffer LFUN that can be dispatched even
1702 // if internal, put a switch '(cmd.action)' here.
1708 switch (cmd.action) {
1710 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1711 flag.setOnOff(isReadonly());
1714 // FIXME: There is need for a command-line import.
1715 //case LFUN_BUFFER_IMPORT:
1717 case LFUN_BUFFER_AUTO_SAVE:
1720 case LFUN_BUFFER_EXPORT_CUSTOM:
1721 // FIXME: Nothing to check here?
1724 case LFUN_BUFFER_EXPORT: {
1725 docstring const arg = cmd.argument();
1726 enable = arg == "custom" || isExportable(to_utf8(arg));
1728 flag.message(bformat(
1729 _("Don't know how to export to format: %1$s"), arg));
1733 case LFUN_BUFFER_CHKTEX:
1734 enable = isLatex() && !lyxrc.chktex_command.empty();
1737 case LFUN_BUILD_PROGRAM:
1738 enable = isExportable("program");
1741 case LFUN_BRANCH_ACTIVATE:
1742 case LFUN_BRANCH_DEACTIVATE: {
1743 BranchList const & branchList = params().branchlist();
1744 docstring const branchName = cmd.argument();
1745 enable = !branchName.empty() && branchList.find(branchName);
1749 case LFUN_BRANCH_ADD:
1750 case LFUN_BRANCHES_RENAME:
1751 case LFUN_BUFFER_PRINT:
1752 // if no Buffer is present, then of course we won't be called!
1755 case LFUN_BUFFER_LANGUAGE:
1756 enable = !isReadonly();
1762 flag.setEnabled(enable);
1767 void Buffer::dispatch(string const & command, DispatchResult & result)
1769 return dispatch(lyxaction.lookupFunc(command), result);
1773 // NOTE We can end up here even if we have no GUI, because we are called
1774 // by LyX::exec to handled command-line requests. So we may need to check
1775 // whether we have a GUI or not. The boolean use_gui holds this information.
1776 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
1779 // FIXME? if there is an Buffer LFUN that can be dispatched even
1780 // if internal, put a switch '(cmd.action)' here.
1781 dr.dispatched(false);
1784 string const argument = to_utf8(func.argument());
1785 // We'll set this back to false if need be.
1786 bool dispatched = true;
1787 undo().beginUndoGroup();
1789 switch (func.action) {
1790 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1791 if (lyxvc().inUse())
1792 lyxvc().toggleReadOnly();
1794 setReadonly(!isReadonly());
1797 case LFUN_BUFFER_EXPORT: {
1798 bool success = doExport(argument, false);
1799 dr.setError(success);
1801 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
1806 case LFUN_BUILD_PROGRAM:
1807 doExport("program", true);
1810 case LFUN_BUFFER_CHKTEX:
1814 case LFUN_BUFFER_EXPORT_CUSTOM: {
1816 string command = split(argument, format_name, ' ');
1817 Format const * format = formats.getFormat(format_name);
1819 lyxerr << "Format \"" << format_name
1820 << "\" not recognized!"
1825 // The name of the file created by the conversion process
1828 // Output to filename
1829 if (format->name() == "lyx") {
1830 string const latexname = latexName(false);
1831 filename = changeExtension(latexname,
1832 format->extension());
1833 filename = addName(temppath(), filename);
1835 if (!writeFile(FileName(filename)))
1839 doExport(format_name, true, filename);
1842 // Substitute $$FName for filename
1843 if (!contains(command, "$$FName"))
1844 command = "( " + command + " ) < $$FName";
1845 command = subst(command, "$$FName", filename);
1847 // Execute the command in the background
1849 call.startscript(Systemcall::DontWait, command);
1853 // FIXME: There is need for a command-line import.
1855 case LFUN_BUFFER_IMPORT:
1860 case LFUN_BUFFER_AUTO_SAVE:
1864 case LFUN_BRANCH_ADD: {
1865 docstring const branch_name = func.argument();
1866 if (branch_name.empty()) {
1870 BranchList & branch_list = params().branchlist();
1871 Branch * branch = branch_list.find(branch_name);
1873 LYXERR0("Branch " << branch_name << " already exists.");
1875 docstring const msg =
1876 bformat(_("Branch \"%1$s\" already exists."), branch_name);
1879 branch_list.add(branch_name);
1880 branch = branch_list.find(branch_name);
1881 string const x11hexname = X11hexname(branch->color());
1882 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
1883 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
1885 dr.update(Update::Force);
1890 case LFUN_BRANCH_ACTIVATE:
1891 case LFUN_BRANCH_DEACTIVATE: {
1892 BranchList & branchList = params().branchlist();
1893 docstring const branchName = func.argument();
1894 // the case without a branch name is handled elsewhere
1895 if (branchName.empty()) {
1899 Branch * branch = branchList.find(branchName);
1901 LYXERR0("Branch " << branchName << " does not exist.");
1903 docstring const msg =
1904 bformat(_("Branch \"%1$s\" does not exist."), branchName);
1907 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1909 dr.update(Update::Force);
1914 case LFUN_BRANCHES_RENAME: {
1915 if (func.argument().empty())
1918 docstring const oldname = from_utf8(func.getArg(0));
1919 docstring const newname = from_utf8(func.getArg(1));
1920 InsetIterator it = inset_iterator_begin(inset());
1921 InsetIterator const end = inset_iterator_end(inset());
1922 bool success = false;
1923 for (; it != end; ++it) {
1924 if (it->lyxCode() == BRANCH_CODE) {
1925 InsetBranch & ins = static_cast<InsetBranch &>(*it);
1926 if (ins.branch() == oldname) {
1927 undo().recordUndo(it);
1928 ins.rename(newname);
1933 if (it->lyxCode() == INCLUDE_CODE) {
1934 // get buffer of external file
1935 InsetInclude const & ins =
1936 static_cast<InsetInclude const &>(*it);
1937 Buffer * child = ins.getChildBuffer();
1940 child->dispatch(func, dr);
1945 dr.update(Update::Force);
1949 case LFUN_BUFFER_PRINT: {
1950 // we'll assume there's a problem until we succeed
1952 string target = func.getArg(0);
1953 string target_name = func.getArg(1);
1954 string command = func.getArg(2);
1957 || target_name.empty()
1958 || command.empty()) {
1959 LYXERR0("Unable to parse " << func.argument());
1960 docstring const msg =
1961 bformat(_("Unable to parse \"%1$s\""), func.argument());
1965 if (target != "printer" && target != "file") {
1966 LYXERR0("Unrecognized target \"" << target << '"');
1967 docstring const msg =
1968 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
1973 if (!doExport("dvi", true)) {
1974 showPrintError(absFileName());
1975 dr.setMessage(_("Error exporting to DVI."));
1979 // Push directory path.
1980 string const path = temppath();
1981 // Prevent the compiler from optimizing away p
1985 // there are three cases here:
1986 // 1. we print to a file
1987 // 2. we print directly to a printer
1988 // 3. we print using a spool command (print to file first)
1991 string const dviname = changeExtension(latexName(true), "dvi");
1993 if (target == "printer") {
1994 if (!lyxrc.print_spool_command.empty()) {
1995 // case 3: print using a spool
1996 string const psname = changeExtension(dviname,".ps");
1997 command += ' ' + lyxrc.print_to_file
2000 + quoteName(dviname);
2002 string command2 = lyxrc.print_spool_command + ' ';
2003 if (target_name != "default") {
2004 command2 += lyxrc.print_spool_printerprefix
2008 command2 += quoteName(psname);
2010 // If successful, then spool command
2011 res = one.startscript(Systemcall::Wait, command);
2014 // If there's no GUI, we have to wait on this command. Otherwise,
2015 // LyX deletes the temporary directory, and with it the spooled
2016 // file, before it can be printed!!
2017 Systemcall::Starttype stype = use_gui ?
2018 Systemcall::DontWait : Systemcall::Wait;
2019 res = one.startscript(stype, command2);
2022 // case 2: print directly to a printer
2023 if (target_name != "default")
2024 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2026 Systemcall::Starttype stype = use_gui ?
2027 Systemcall::DontWait : Systemcall::Wait;
2028 res = one.startscript(stype, command + quoteName(dviname));
2032 // case 1: print to a file
2033 FileName const filename(makeAbsPath(target_name, filePath()));
2034 FileName const dvifile(makeAbsPath(dviname, path));
2035 if (filename.exists()) {
2036 docstring text = bformat(
2037 _("The file %1$s already exists.\n\n"
2038 "Do you want to overwrite that file?"),
2039 makeDisplayPath(filename.absFilename()));
2040 if (Alert::prompt(_("Overwrite file?"),
2041 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2044 command += ' ' + lyxrc.print_to_file
2045 + quoteName(filename.toFilesystemEncoding())
2047 + quoteName(dvifile.toFilesystemEncoding());
2049 Systemcall::Starttype stype = use_gui ?
2050 Systemcall::DontWait : Systemcall::Wait;
2051 res = one.startscript(stype, command);
2057 dr.setMessage(_("Error running external commands."));
2058 showPrintError(absFileName());
2063 case LFUN_BUFFER_LANGUAGE: {
2064 Language const * oldL = params().language;
2065 Language const * newL = languages.getLanguage(argument);
2066 if (!newL || oldL == newL)
2068 if (oldL->rightToLeft() == newL->rightToLeft() && !isMultiLingual())
2069 changeLanguage(oldL, newL);
2077 dr.dispatched(dispatched);
2078 undo().endUndoGroup();
2082 void Buffer::changeLanguage(Language const * from, Language const * to)
2084 LASSERT(from, /**/);
2087 for_each(par_iterator_begin(),
2089 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2093 bool Buffer::isMultiLingual() const
2095 ParConstIterator end = par_iterator_end();
2096 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2097 if (it->isMultiLingual(params()))
2104 DocIterator Buffer::getParFromID(int const id) const
2106 Buffer * buf = const_cast<Buffer *>(this);
2108 // John says this is called with id == -1 from undo
2109 lyxerr << "getParFromID(), id: " << id << endl;
2110 return doc_iterator_end(buf);
2113 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2114 if (it.paragraph().id() == id)
2117 return doc_iterator_end(buf);
2121 bool Buffer::hasParWithID(int const id) const
2123 return !getParFromID(id).atEnd();
2127 ParIterator Buffer::par_iterator_begin()
2129 return ParIterator(doc_iterator_begin(this));
2133 ParIterator Buffer::par_iterator_end()
2135 return ParIterator(doc_iterator_end(this));
2139 ParConstIterator Buffer::par_iterator_begin() const
2141 return ParConstIterator(doc_iterator_begin(this));
2145 ParConstIterator Buffer::par_iterator_end() const
2147 return ParConstIterator(doc_iterator_end(this));
2151 Language const * Buffer::language() const
2153 return params().language;
2157 docstring const Buffer::B_(string const & l10n) const
2159 return params().B_(l10n);
2163 bool Buffer::isClean() const
2165 return d->lyx_clean;
2169 bool Buffer::isBakClean() const
2171 return d->bak_clean;
2175 bool Buffer::isExternallyModified(CheckMethod method) const
2177 LASSERT(d->filename.exists(), /**/);
2178 // if method == timestamp, check timestamp before checksum
2179 return (method == checksum_method
2180 || d->timestamp_ != d->filename.lastModified())
2181 && d->checksum_ != d->filename.checksum();
2185 void Buffer::saveCheckSum(FileName const & file) const
2187 if (file.exists()) {
2188 d->timestamp_ = file.lastModified();
2189 d->checksum_ = file.checksum();
2191 // in the case of save to a new file.
2198 void Buffer::markClean() const
2200 if (!d->lyx_clean) {
2201 d->lyx_clean = true;
2204 // if the .lyx file has been saved, we don't need an
2206 d->bak_clean = true;
2210 void Buffer::markBakClean() const
2212 d->bak_clean = true;
2216 void Buffer::setUnnamed(bool flag)
2222 bool Buffer::isUnnamed() const
2229 /// Don't check unnamed, here: isInternal() is used in
2230 /// newBuffer(), where the unnamed flag has not been set by anyone
2231 /// yet. Also, for an internal buffer, there should be no need for
2232 /// retrieving fileName() nor for checking if it is unnamed or not.
2233 bool Buffer::isInternal() const
2235 return fileName().extension() == "internal";
2239 void Buffer::markDirty()
2242 d->lyx_clean = false;
2245 d->bak_clean = false;
2247 DepClean::iterator it = d->dep_clean.begin();
2248 DepClean::const_iterator const end = d->dep_clean.end();
2250 for (; it != end; ++it)
2255 FileName Buffer::fileName() const
2261 string Buffer::absFileName() const
2263 return d->filename.absFilename();
2267 string Buffer::filePath() const
2269 return d->filename.onlyPath().absFilename() + "/";
2273 bool Buffer::isReadonly() const
2275 return d->read_only;
2279 void Buffer::setParent(Buffer const * buffer)
2281 // Avoids recursive include.
2282 d->setParent(buffer == this ? 0 : buffer);
2287 Buffer const * Buffer::parent() const
2293 void Buffer::collectRelatives(BufferSet & bufs) const
2297 parent()->collectRelatives(bufs);
2299 // loop over children
2300 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2301 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2302 for (; it != end; ++it)
2303 bufs.insert(const_cast<Buffer *>(it->first));
2307 std::vector<Buffer const *> Buffer::allRelatives() const
2310 collectRelatives(bufs);
2311 BufferSet::iterator it = bufs.begin();
2312 std::vector<Buffer const *> ret;
2313 for (; it != bufs.end(); ++it)
2319 Buffer const * Buffer::masterBuffer() const
2321 Buffer const * const pbuf = d->parent();
2325 return pbuf->masterBuffer();
2329 bool Buffer::isChild(Buffer * child) const
2331 return d->children_positions.find(child) != d->children_positions.end();
2335 DocIterator Buffer::firstChildPosition(Buffer const * child)
2337 Impl::BufferPositionMap::iterator it;
2338 it = d->children_positions.find(child);
2339 if (it == d->children_positions.end())
2340 return DocIterator(this);
2345 void Buffer::getChildren(std::vector<Buffer *> & clist, bool grand_children) const
2347 // loop over children
2348 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2349 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2350 for (; it != end; ++it) {
2351 Buffer * child = const_cast<Buffer *>(it->first);
2352 clist.push_back(child);
2353 if (grand_children) {
2354 // there might be grandchildren
2355 std::vector<Buffer *> glist = child->getChildren();
2356 for (vector<Buffer *>::const_iterator git = glist.begin();
2357 git != glist.end(); ++git)
2358 clist.push_back(*git);
2364 std::vector<Buffer *> Buffer::getChildren(bool grand_children) const
2366 std::vector<Buffer *> v;
2367 getChildren(v, grand_children);
2372 template<typename M>
2373 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
2378 typename M::iterator it = m.lower_bound(x);
2379 if (it == m.begin())
2387 MacroData const * Buffer::getBufferMacro(docstring const & name,
2388 DocIterator const & pos) const
2390 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2392 // if paragraphs have no macro context set, pos will be empty
2396 // we haven't found anything yet
2397 DocIterator bestPos = par_iterator_begin();
2398 MacroData const * bestData = 0;
2400 // find macro definitions for name
2401 Impl::NamePositionScopeMacroMap::iterator nameIt
2402 = d->macros.find(name);
2403 if (nameIt != d->macros.end()) {
2404 // find last definition in front of pos or at pos itself
2405 Impl::PositionScopeMacroMap::const_iterator it
2406 = greatest_below(nameIt->second, pos);
2407 if (it != nameIt->second.end()) {
2409 // scope ends behind pos?
2410 if (pos < it->second.first) {
2411 // Looks good, remember this. If there
2412 // is no external macro behind this,
2413 // we found the right one already.
2414 bestPos = it->first;
2415 bestData = &it->second.second;
2419 // try previous macro if there is one
2420 if (it == nameIt->second.begin())
2427 // find macros in included files
2428 Impl::PositionScopeBufferMap::const_iterator it
2429 = greatest_below(d->position_to_children, pos);
2430 if (it == d->position_to_children.end())
2431 // no children before
2435 // do we know something better (i.e. later) already?
2436 if (it->first < bestPos )
2439 // scope ends behind pos?
2440 if (pos < it->second.first) {
2441 // look for macro in external file
2442 d->macro_lock = true;
2443 MacroData const * data
2444 = it->second.second->getMacro(name, false);
2445 d->macro_lock = false;
2447 bestPos = it->first;
2453 // try previous file if there is one
2454 if (it == d->position_to_children.begin())
2459 // return the best macro we have found
2464 MacroData const * Buffer::getMacro(docstring const & name,
2465 DocIterator const & pos, bool global) const
2470 // query buffer macros
2471 MacroData const * data = getBufferMacro(name, pos);
2475 // If there is a master buffer, query that
2476 Buffer const * const pbuf = d->parent();
2478 d->macro_lock = true;
2479 MacroData const * macro = pbuf->getMacro(
2480 name, *this, false);
2481 d->macro_lock = false;
2487 data = MacroTable::globalMacros().get(name);
2496 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2498 // set scope end behind the last paragraph
2499 DocIterator scope = par_iterator_begin();
2500 scope.pit() = scope.lastpit() + 1;
2502 return getMacro(name, scope, global);
2506 MacroData const * Buffer::getMacro(docstring const & name,
2507 Buffer const & child, bool global) const
2509 // look where the child buffer is included first
2510 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2511 if (it == d->children_positions.end())
2514 // check for macros at the inclusion position
2515 return getMacro(name, it->second, global);
2519 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
2521 pit_type lastpit = it.lastpit();
2523 // look for macros in each paragraph
2524 while (it.pit() <= lastpit) {
2525 Paragraph & par = it.paragraph();
2527 // iterate over the insets of the current paragraph
2528 InsetList const & insets = par.insetList();
2529 InsetList::const_iterator iit = insets.begin();
2530 InsetList::const_iterator end = insets.end();
2531 for (; iit != end; ++iit) {
2532 it.pos() = iit->pos;
2534 // is it a nested text inset?
2535 if (iit->inset->asInsetText()) {
2536 // Inset needs its own scope?
2537 InsetText const * itext = iit->inset->asInsetText();
2538 bool newScope = itext->isMacroScope();
2540 // scope which ends just behind the inset
2541 DocIterator insetScope = it;
2544 // collect macros in inset
2545 it.push_back(CursorSlice(*iit->inset));
2546 updateMacros(it, newScope ? insetScope : scope);
2551 // is it an external file?
2552 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2553 // get buffer of external file
2554 InsetInclude const & inset =
2555 static_cast<InsetInclude const &>(*iit->inset);
2556 d->macro_lock = true;
2557 Buffer * child = inset.getChildBuffer();
2558 d->macro_lock = false;
2562 // register its position, but only when it is
2563 // included first in the buffer
2564 if (d->children_positions.find(child) ==
2565 d->children_positions.end())
2566 d->children_positions[child] = it;
2568 // register child with its scope
2569 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
2573 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2577 MathMacroTemplate & macroTemplate =
2578 static_cast<MathMacroTemplate &>(*iit->inset);
2579 MacroContext mc(this, it);
2580 macroTemplate.updateToContext(mc);
2583 bool valid = macroTemplate.validMacro();
2584 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2585 // then the BufferView's cursor will be invalid in
2586 // some cases which leads to crashes.
2591 // FIXME (Abdel), I don't understandt why we pass 'it' here
2592 // instead of 'macroTemplate' defined above... is this correct?
2593 d->macros[macroTemplate.name()][it] =
2594 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(this), it));
2604 void Buffer::updateMacros() const
2609 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2611 // start with empty table
2613 d->children_positions.clear();
2614 d->position_to_children.clear();
2616 // Iterate over buffer, starting with first paragraph
2617 // The scope must be bigger than any lookup DocIterator
2618 // later. For the global lookup, lastpit+1 is used, hence
2619 // we use lastpit+2 here.
2620 DocIterator it = par_iterator_begin();
2621 DocIterator outerScope = it;
2622 outerScope.pit() = outerScope.lastpit() + 2;
2623 updateMacros(it, outerScope);
2627 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2629 InsetIterator it = inset_iterator_begin(inset());
2630 InsetIterator const end = inset_iterator_end(inset());
2631 for (; it != end; ++it) {
2632 if (it->lyxCode() == BRANCH_CODE) {
2633 InsetBranch & br = static_cast<InsetBranch &>(*it);
2634 docstring const name = br.branch();
2635 if (!from_master && !params().branchlist().find(name))
2636 result.push_back(name);
2637 else if (from_master && !masterBuffer()->params().branchlist().find(name))
2638 result.push_back(name);
2641 if (it->lyxCode() == INCLUDE_CODE) {
2642 // get buffer of external file
2643 InsetInclude const & ins =
2644 static_cast<InsetInclude const &>(*it);
2645 Buffer * child = ins.getChildBuffer();
2648 child->getUsedBranches(result, true);
2651 // remove duplicates
2656 void Buffer::updateMacroInstances() const
2658 LYXERR(Debug::MACROS, "updateMacroInstances for "
2659 << d->filename.onlyFileName());
2660 DocIterator it = doc_iterator_begin(this);
2662 DocIterator const end = doc_iterator_end(this);
2663 for (; it != end; it.forwardInset()) {
2664 // look for MathData cells in InsetMathNest insets
2665 InsetMath * minset = it.nextInset()->asInsetMath();
2669 // update macro in all cells of the InsetMathNest
2670 DocIterator::idx_type n = minset->nargs();
2671 MacroContext mc = MacroContext(this, it);
2672 for (DocIterator::idx_type i = 0; i < n; ++i) {
2673 MathData & data = minset->cell(i);
2674 data.updateMacros(0, mc);
2680 void Buffer::listMacroNames(MacroNameSet & macros) const
2685 d->macro_lock = true;
2687 // loop over macro names
2688 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2689 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2690 for (; nameIt != nameEnd; ++nameIt)
2691 macros.insert(nameIt->first);
2693 // loop over children
2694 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2695 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2696 for (; it != end; ++it)
2697 it->first->listMacroNames(macros);
2700 Buffer const * const pbuf = d->parent();
2702 pbuf->listMacroNames(macros);
2704 d->macro_lock = false;
2708 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2710 Buffer const * const pbuf = d->parent();
2715 pbuf->listMacroNames(names);
2718 MacroNameSet::iterator it = names.begin();
2719 MacroNameSet::iterator end = names.end();
2720 for (; it != end; ++it) {
2722 MacroData const * data =
2723 pbuf->getMacro(*it, *this, false);
2725 macros.insert(data);
2727 // we cannot access the original MathMacroTemplate anymore
2728 // here to calls validate method. So we do its work here manually.
2729 // FIXME: somehow make the template accessible here.
2730 if (data->optionals() > 0)
2731 features.require("xargs");
2737 Buffer::References & Buffer::references(docstring const & label)
2740 return const_cast<Buffer *>(masterBuffer())->references(label);
2742 RefCache::iterator it = d->ref_cache_.find(label);
2743 if (it != d->ref_cache_.end())
2744 return it->second.second;
2746 static InsetLabel const * dummy_il = 0;
2747 static References const dummy_refs;
2748 it = d->ref_cache_.insert(
2749 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2750 return it->second.second;
2754 Buffer::References const & Buffer::references(docstring const & label) const
2756 return const_cast<Buffer *>(this)->references(label);
2760 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2762 masterBuffer()->d->ref_cache_[label].first = il;
2766 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2768 return masterBuffer()->d->ref_cache_[label].first;
2772 void Buffer::clearReferenceCache() const
2775 d->ref_cache_.clear();
2779 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2782 //FIXME: This does not work for child documents yet.
2783 LASSERT(code == CITE_CODE, /**/);
2784 // Check if the label 'from' appears more than once
2785 vector<docstring> labels;
2787 BiblioInfo const & keys = masterBibInfo();
2788 BiblioInfo::const_iterator bit = keys.begin();
2789 BiblioInfo::const_iterator bend = keys.end();
2791 for (; bit != bend; ++bit)
2793 labels.push_back(bit->first);
2796 if (count(labels.begin(), labels.end(), from) > 1)
2799 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2800 if (it->lyxCode() == code) {
2801 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2802 docstring const oldValue = inset.getParam(paramName);
2803 if (oldValue == from)
2804 inset.setParam(paramName, to);
2810 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2811 pit_type par_end, bool full_source) const
2813 OutputParams runparams(¶ms().encoding());
2814 runparams.nice = true;
2815 runparams.flavor = params().useXetex ?
2816 OutputParams::XETEX : OutputParams::LATEX;
2817 runparams.linelen = lyxrc.plaintext_linelen;
2818 // No side effect of file copying and image conversion
2819 runparams.dryrun = true;
2822 os << "% " << _("Preview source code") << "\n\n";
2824 d->texrow.newline();
2825 d->texrow.newline();
2827 writeDocBookSource(os, absFileName(), runparams, false);
2829 // latex or literate
2830 writeLaTeXSource(os, string(), runparams, true, true);
2832 runparams.par_begin = par_begin;
2833 runparams.par_end = par_end;
2834 if (par_begin + 1 == par_end) {
2836 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2840 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2841 convert<docstring>(par_begin),
2842 convert<docstring>(par_end - 1))
2849 // output paragraphs
2851 docbookParagraphs(text(), *this, os, runparams);
2853 // latex or literate
2854 latexParagraphs(*this, text(), os, texrow, runparams);
2859 ErrorList & Buffer::errorList(string const & type) const
2861 static ErrorList emptyErrorList;
2862 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2863 if (I == d->errorLists.end())
2864 return emptyErrorList;
2870 void Buffer::updateTocItem(std::string const & type,
2871 DocIterator const & dit) const
2874 gui_->updateTocItem(type, dit);
2878 void Buffer::structureChanged() const
2881 gui_->structureChanged();
2885 void Buffer::errors(string const & err, bool from_master) const
2888 gui_->errors(err, from_master);
2892 void Buffer::message(docstring const & msg) const
2899 void Buffer::setBusy(bool on) const
2906 void Buffer::setReadOnly(bool on) const
2909 d->wa_->setReadOnly(on);
2913 void Buffer::updateTitles() const
2916 d->wa_->updateTitles();
2920 void Buffer::resetAutosaveTimers() const
2923 gui_->resetAutosaveTimers();
2927 bool Buffer::hasGuiDelegate() const
2933 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2942 class AutoSaveBuffer : public ForkedProcess {
2945 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2946 : buffer_(buffer), fname_(fname) {}
2948 virtual boost::shared_ptr<ForkedProcess> clone() const
2950 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2955 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2956 from_utf8(fname_.absFilename())));
2957 return run(DontWait);
2961 virtual int generateChild();
2963 Buffer const & buffer_;
2968 int AutoSaveBuffer::generateChild()
2970 #if defined(__APPLE__)
2971 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
2972 * We should use something else like threads.
2974 * Since I do not know how to determine at run time what is the OS X
2975 * version, I just disable forking altogether for now (JMarc)
2977 pid_t const pid = -1;
2979 // tmp_ret will be located (usually) in /tmp
2980 // will that be a problem?
2981 // Note that this calls ForkedCalls::fork(), so it's
2982 // ok cross-platform.
2983 pid_t const pid = fork();
2984 // If you want to debug the autosave
2985 // you should set pid to -1, and comment out the fork.
2986 if (pid != 0 && pid != -1)
2990 // pid = -1 signifies that lyx was unable
2991 // to fork. But we will do the save
2993 bool failed = false;
2994 FileName const tmp_ret = FileName::tempName("lyxauto");
2995 if (!tmp_ret.empty()) {
2996 buffer_.writeFile(tmp_ret);
2997 // assume successful write of tmp_ret
2998 if (!tmp_ret.moveTo(fname_))
3004 // failed to write/rename tmp_ret so try writing direct
3005 if (!buffer_.writeFile(fname_)) {
3006 // It is dangerous to do this in the child,
3007 // but safe in the parent, so...
3008 if (pid == -1) // emit message signal.
3009 buffer_.message(_("Autosave failed!"));
3013 if (pid == 0) // we are the child so...
3022 FileName Buffer::getAutosaveFilename() const
3024 // if the document is unnamed try to save in the backup dir, else
3025 // in the default document path, and as a last try in the filePath,
3026 // which will most often be the temporary directory
3029 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3030 : lyxrc.backupdir_path;
3031 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3034 string const fname = "#" + d->filename.onlyFileName() + "#";
3035 return makeAbsPath(fname, fpath);
3039 void Buffer::removeAutosaveFile() const
3041 FileName const f = getAutosaveFilename();
3047 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3049 FileName const newauto = getAutosaveFilename();
3050 if (!(oldauto == newauto || oldauto.moveTo(newauto)))
3051 LYXERR0("Unable to remove autosave file `" << oldauto << "'!");
3055 // Perfect target for a thread...
3056 void Buffer::autoSave() const
3058 if (isBakClean() || isReadonly()) {
3059 // We don't save now, but we'll try again later
3060 resetAutosaveTimers();
3064 // emit message signal.
3065 message(_("Autosaving current document..."));
3066 AutoSaveBuffer autosave(*this, getAutosaveFilename());
3070 resetAutosaveTimers();
3074 string Buffer::bufferFormat() const
3076 string format = params().documentClass().outputFormat();
3077 if (format == "latex") {
3078 if (params().useXetex)
3080 if (params().encoding().package() == Encoding::japanese)
3087 string Buffer::getDefaultOutputFormat() const
3089 if (!params().defaultOutputFormat.empty()
3090 && params().defaultOutputFormat != "default")
3091 return params().defaultOutputFormat;
3092 typedef vector<Format const *> Formats;
3093 Formats formats = exportableFormats(true);
3096 || params().useXetex
3097 || params().encoding().package() == Encoding::japanese) {
3098 if (formats.empty())
3100 // return the first we find
3101 return formats.front()->name();
3103 return lyxrc.default_view_format;
3108 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3109 string & result_file) const
3111 string backend_format;
3112 OutputParams runparams(¶ms().encoding());
3113 runparams.flavor = OutputParams::LATEX;
3114 runparams.linelen = lyxrc.plaintext_linelen;
3115 vector<string> backs = backends();
3116 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3117 // Get shortest path to format
3118 Graph::EdgePath path;
3119 for (vector<string>::const_iterator it = backs.begin();
3120 it != backs.end(); ++it) {
3121 Graph::EdgePath p = theConverters().getPath(*it, format);
3122 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3123 backend_format = *it;
3128 if (!put_in_tempdir) {
3129 // Only show this alert if this is an export to a non-temporary
3130 // file (not for previewing).
3131 Alert::error(_("Couldn't export file"), bformat(
3132 _("No information for exporting the format %1$s."),
3133 formats.prettyName(format)));
3137 runparams.flavor = theConverters().getFlavor(path);
3140 backend_format = format;
3141 // FIXME: Don't hardcode format names here, but use a flag
3142 if (backend_format == "pdflatex")
3143 runparams.flavor = OutputParams::PDFLATEX;
3146 string filename = latexName(false);
3147 filename = addName(temppath(), filename);
3148 filename = changeExtension(filename,
3149 formats.extension(backend_format));
3152 updateMacroInstances();
3154 // Plain text backend
3155 if (backend_format == "text") {
3156 runparams.flavor = OutputParams::TEXT;
3157 writePlaintextFile(*this, FileName(filename), runparams);
3160 else if (backend_format == "xhtml") {
3161 runparams.flavor = OutputParams::HTML;
3162 makeLyXHTMLFile(FileName(filename), runparams);
3163 } else if (backend_format == "lyx")
3164 writeFile(FileName(filename));
3166 else if (isDocBook()) {
3167 runparams.nice = !put_in_tempdir;
3168 makeDocBookFile(FileName(filename), runparams);
3171 else if (backend_format == format) {
3172 runparams.nice = true;
3173 if (!makeLaTeXFile(FileName(filename), string(), runparams))
3175 } else if (!lyxrc.tex_allows_spaces
3176 && contains(filePath(), ' ')) {
3177 Alert::error(_("File name error"),
3178 _("The directory path to the document cannot contain spaces."));
3181 runparams.nice = false;
3182 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
3186 string const error_type = (format == "program")
3187 ? "Build" : bufferFormat();
3188 ErrorList & error_list = d->errorLists[error_type];
3189 string const ext = formats.extension(format);
3190 FileName const tmp_result_file(changeExtension(filename, ext));
3191 bool const success = theConverters().convert(this, FileName(filename),
3192 tmp_result_file, FileName(absFileName()), backend_format, format,
3194 // Emit the signal to show the error list.
3195 if (format != backend_format) {
3197 // also to the children, in case of master-buffer-view
3198 std::vector<Buffer *> clist = getChildren();
3199 for (vector<Buffer *>::const_iterator cit = clist.begin();
3200 cit != clist.end(); ++cit)
3201 (*cit)->errors(error_type, true);
3206 if (put_in_tempdir) {
3207 result_file = tmp_result_file.absFilename();
3211 result_file = changeExtension(exportFileName().absFilename(), ext);
3212 // We need to copy referenced files (e. g. included graphics
3213 // if format == "dvi") to the result dir.
3214 vector<ExportedFile> const files =
3215 runparams.exportdata->externalFiles(format);
3216 string const dest = onlyPath(result_file);
3217 CopyStatus status = SUCCESS;
3218 for (vector<ExportedFile>::const_iterator it = files.begin();
3219 it != files.end() && status != CANCEL; ++it) {
3220 string const fmt = formats.getFormatFromFile(it->sourceName);
3221 status = copyFile(fmt, it->sourceName,
3222 makeAbsPath(it->exportName, dest),
3223 it->exportName, status == FORCE);
3225 if (status == CANCEL) {
3226 message(_("Document export cancelled."));
3227 } else if (tmp_result_file.exists()) {
3228 // Finally copy the main file
3229 status = copyFile(format, tmp_result_file,
3230 FileName(result_file), result_file,
3232 message(bformat(_("Document exported as %1$s "
3234 formats.prettyName(format),
3235 makeDisplayPath(result_file)));
3237 // This must be a dummy converter like fax (bug 1888)
3238 message(bformat(_("Document exported as %1$s"),
3239 formats.prettyName(format)));
3246 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
3249 return doExport(format, put_in_tempdir, result_file);
3253 bool Buffer::preview(string const & format) const
3256 if (!doExport(format, true, result_file))
3258 return formats.view(*this, FileName(result_file), format);
3262 bool Buffer::isExportable(string const & format) const
3264 vector<string> backs = backends();
3265 for (vector<string>::const_iterator it = backs.begin();
3266 it != backs.end(); ++it)
3267 if (theConverters().isReachable(*it, format))
3273 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
3275 vector<string> const backs = backends();
3276 vector<Format const *> result =
3277 theConverters().getReachable(backs[0], only_viewable, true);
3278 for (vector<string>::const_iterator it = backs.begin() + 1;
3279 it != backs.end(); ++it) {
3280 vector<Format const *> r =
3281 theConverters().getReachable(*it, only_viewable, false);
3282 result.insert(result.end(), r.begin(), r.end());
3288 vector<string> Buffer::backends() const
3291 v.push_back(bufferFormat());
3292 // FIXME: Don't hardcode format names here, but use a flag
3293 if (v.back() == "latex")
3294 v.push_back("pdflatex");
3295 v.push_back("xhtml");
3296 v.push_back("text");
3302 bool Buffer::readFileHelper(FileName const & s)
3304 // File information about normal file
3306 docstring const file = makeDisplayPath(s.absFilename(), 50);
3307 docstring text = bformat(_("The specified document\n%1$s"
3308 "\ncould not be read."), file);
3309 Alert::error(_("Could not read document"), text);
3313 // Check if emergency save file exists and is newer.
3314 FileName const e(s.absFilename() + ".emergency");
3316 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
3317 docstring const file = makeDisplayPath(s.absFilename(), 20);
3318 docstring const text =
3319 bformat(_("An emergency save of the document "
3321 "Recover emergency save?"), file);
3322 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
3323 _("&Recover"), _("&Load Original"),
3327 // the file is not saved if we load the emergency file.
3332 if ((res = readFile(e)) == success)
3333 str = _("Document was successfully recovered.");
3335 str = _("Document was NOT successfully recovered.");
3336 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3337 from_utf8(e.absFilename()));
3339 if (!Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3340 _("&Remove"), _("&Keep it"))) {
3343 Alert::warning(_("Emergency file deleted"),
3344 _("Do not forget to save your file now!"), true);
3349 if (!Alert::prompt(_("Delete emergency file?"),
3350 _("Remove emergency file now?"), 1, 1,
3351 _("&Remove"), _("&Keep it")))
3359 // Now check if autosave file is newer.
3360 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
3362 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
3363 docstring const file = makeDisplayPath(s.absFilename(), 20);
3364 docstring const text =
3365 bformat(_("The backup of the document "
3366 "%1$s is newer.\n\nLoad the "
3367 "backup instead?"), file);
3368 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
3369 _("&Load backup"), _("Load &original"),
3373 // the file is not saved if we load the autosave file.
3377 // Here we delete the autosave
3388 bool Buffer::loadLyXFile(FileName const & s)
3390 if (s.isReadableFile()) {
3391 if (readFileHelper(s)) {
3392 lyxvc().file_found_hook(s);
3393 if (!s.isWritable())
3398 docstring const file = makeDisplayPath(s.absFilename(), 20);
3399 // Here we probably should run
3400 if (LyXVC::file_not_found_hook(s)) {
3401 docstring const text =
3402 bformat(_("Do you want to retrieve the document"
3403 " %1$s from version control?"), file);
3404 int const ret = Alert::prompt(_("Retrieve from version control?"),
3405 text, 0, 1, _("&Retrieve"), _("&Cancel"));
3408 // How can we know _how_ to do the checkout?
3409 // With the current VC support it has to be,
3410 // a RCS file since CVS do not have special ,v files.
3412 return loadLyXFile(s);
3420 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3422 TeXErrors::Errors::const_iterator cit = terr.begin();
3423 TeXErrors::Errors::const_iterator end = terr.end();
3425 for (; cit != end; ++cit) {
3428 int errorRow = cit->error_in_line;
3429 bool found = d->texrow.getIdFromRow(errorRow, id_start,
3435 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
3436 } while (found && id_start == id_end && pos_start == pos_end);
3438 errorList.push_back(ErrorItem(cit->error_desc,
3439 cit->error_text, id_start, pos_start, pos_end));
3444 void Buffer::setBuffersForInsets() const
3446 inset().setBuffer(const_cast<Buffer &>(*this));
3450 void Buffer::updateLabels(UpdateScope scope, bool out) const
3452 // Use the master text class also for child documents
3453 Buffer const * const master = masterBuffer();
3454 DocumentClass const & textclass = master->params().documentClass();
3456 // keep the buffers to be children in this set. If the call from the
3457 // master comes back we can see which of them were actually seen (i.e.
3458 // via an InsetInclude). The remaining ones in the set need still be updated.
3459 static std::set<Buffer const *> bufToUpdate;
3460 if (scope == UpdateMaster) {
3461 // If this is a child document start with the master
3462 if (master != this) {
3463 bufToUpdate.insert(this);
3464 master->updateLabels(UpdateMaster, out);
3465 // Do this here in case the master has no gui associated with it. Then,
3466 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3470 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3471 if (bufToUpdate.find(this) == bufToUpdate.end())
3475 // start over the counters in the master
3476 textclass.counters().reset();
3479 // update will be done below for this buffer
3480 bufToUpdate.erase(this);
3482 // update all caches
3483 clearReferenceCache();
3486 Buffer & cbuf = const_cast<Buffer &>(*this);
3488 LASSERT(!text().paragraphs().empty(), /**/);
3491 ParIterator parit = cbuf.par_iterator_begin();
3492 updateLabels(parit, out);
3495 // TocBackend update will be done later.
3498 cbuf.tocBackend().update();
3499 if (scope == UpdateMaster)
3500 cbuf.structureChanged();
3504 static depth_type getDepth(DocIterator const & it)
3506 depth_type depth = 0;
3507 for (size_t i = 0 ; i < it.depth() ; ++i)
3508 if (!it[i].inset().inMathed())
3509 depth += it[i].paragraph().getDepth() + 1;
3510 // remove 1 since the outer inset does not count
3514 static depth_type getItemDepth(ParIterator const & it)
3516 Paragraph const & par = *it;
3517 LabelType const labeltype = par.layout().labeltype;
3519 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3522 // this will hold the lowest depth encountered up to now.
3523 depth_type min_depth = getDepth(it);
3524 ParIterator prev_it = it;
3527 --prev_it.top().pit();
3529 // start of nested inset: go to outer par
3531 if (prev_it.empty()) {
3532 // start of document: nothing to do
3537 // We search for the first paragraph with same label
3538 // that is not more deeply nested.
3539 Paragraph & prev_par = *prev_it;
3540 depth_type const prev_depth = getDepth(prev_it);
3541 if (labeltype == prev_par.layout().labeltype) {
3542 if (prev_depth < min_depth)
3543 return prev_par.itemdepth + 1;
3544 if (prev_depth == min_depth)
3545 return prev_par.itemdepth;
3547 min_depth = min(min_depth, prev_depth);
3548 // small optimization: if we are at depth 0, we won't
3549 // find anything else
3550 if (prev_depth == 0)
3556 static bool needEnumCounterReset(ParIterator const & it)
3558 Paragraph const & par = *it;
3559 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3560 depth_type const cur_depth = par.getDepth();
3561 ParIterator prev_it = it;
3562 while (prev_it.pit()) {
3563 --prev_it.top().pit();
3564 Paragraph const & prev_par = *prev_it;
3565 if (prev_par.getDepth() <= cur_depth)
3566 return prev_par.layout().labeltype != LABEL_ENUMERATE;
3568 // start of nested inset: reset
3573 // set the label of a paragraph. This includes the counters.
3574 void Buffer::setLabel(ParIterator & it) const
3576 BufferParams const & bp = this->masterBuffer()->params();
3577 DocumentClass const & textclass = bp.documentClass();
3578 Paragraph & par = it.paragraph();
3579 Layout const & layout = par.layout();
3580 Counters & counters = textclass.counters();
3582 if (par.params().startOfAppendix()) {
3583 // FIXME: only the counter corresponding to toplevel
3584 // sectioning should be reset
3586 counters.appendix(true);
3588 par.params().appendix(counters.appendix());
3590 // Compute the item depth of the paragraph
3591 par.itemdepth = getItemDepth(it);
3593 if (layout.margintype == MARGIN_MANUAL
3594 || layout.latextype == LATEX_BIB_ENVIRONMENT) {
3595 if (par.params().labelWidthString().empty())
3596 par.params().labelWidthString(par.expandLabel(layout, bp));
3598 par.params().labelWidthString(docstring());
3601 switch(layout.labeltype) {
3603 if (layout.toclevel <= bp.secnumdepth
3604 && (layout.latextype != LATEX_ENVIRONMENT
3605 || it.text()->isFirstInSequence(it.pit()))) {
3606 counters.step(layout.counter);
3607 par.params().labelString(
3608 par.expandLabel(layout, bp));
3610 par.params().labelString(docstring());
3613 case LABEL_ITEMIZE: {
3614 // At some point of time we should do something more
3615 // clever here, like:
3616 // par.params().labelString(
3617 // bp.user_defined_bullet(par.itemdepth).getText());
3618 // for now, use a simple hardcoded label
3619 docstring itemlabel;
3620 switch (par.itemdepth) {
3622 itemlabel = char_type(0x2022);
3625 itemlabel = char_type(0x2013);
3628 itemlabel = char_type(0x2217);
3631 itemlabel = char_type(0x2219); // or 0x00b7
3634 par.params().labelString(itemlabel);
3638 case LABEL_ENUMERATE: {
3639 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
3641 switch (par.itemdepth) {
3650 enumcounter += "iv";
3653 // not a valid enumdepth...
3657 // Maybe we have to reset the enumeration counter.
3658 if (needEnumCounterReset(it))
3659 counters.reset(enumcounter);
3660 counters.step(enumcounter);
3662 string const & lang = par.getParLanguage(bp)->code();
3663 par.params().labelString(counters.theCounter(enumcounter, lang));
3668 case LABEL_SENSITIVE: {
3669 string const & type = counters.current_float();
3670 docstring full_label;
3672 full_label = this->B_("Senseless!!! ");
3674 docstring name = this->B_(textclass.floats().getType(type).name());
3675 if (counters.hasCounter(from_utf8(type))) {
3676 string const & lang = par.getParLanguage(bp)->code();
3677 counters.step(from_utf8(type));
3678 full_label = bformat(from_ascii("%1$s %2$s:"),
3680 counters.theCounter(from_utf8(type), lang));
3682 full_label = bformat(from_ascii("%1$s #:"), name);
3684 par.params().labelString(full_label);
3688 case LABEL_NO_LABEL:
3689 par.params().labelString(docstring());
3693 case LABEL_TOP_ENVIRONMENT:
3694 case LABEL_CENTERED_TOP_ENVIRONMENT:
3697 par.params().labelString(par.expandLabel(layout, bp));
3703 void Buffer::updateLabels(ParIterator & parit, bool out) const
3705 LASSERT(parit.pit() == 0, /**/);
3707 // set the position of the text in the buffer to be able
3708 // to resolve macros in it. This has nothing to do with
3709 // labels, but by putting it here we avoid implementing
3710 // a whole bunch of traversal routines just for this call.
3711 parit.text()->setMacrocontextPosition(parit);
3713 depth_type maxdepth = 0;
3714 pit_type const lastpit = parit.lastpit();
3715 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
3716 // reduce depth if necessary
3717 parit->params().depth(min(parit->params().depth(), maxdepth));
3718 maxdepth = parit->getMaxDepthAfter();
3720 // set the counter for this paragraph
3724 InsetList::const_iterator iit = parit->insetList().begin();
3725 InsetList::const_iterator end = parit->insetList().end();
3726 for (; iit != end; ++iit) {
3727 parit.pos() = iit->pos;
3728 iit->inset->updateLabels(parit, out);
3734 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
3735 WordLangTuple & word_lang, docstring_list & suggestions) const
3739 suggestions.clear();
3740 word_lang = WordLangTuple();
3741 // OK, we start from here.
3742 DocIterator const end = doc_iterator_end(this);
3743 for (; from != end; from.forwardPos()) {
3744 // We are only interested in text so remove the math CursorSlice.
3745 while (from.inMathed()) {
3749 // If from is at the end of the document (which is possible
3750 // when leaving the mathed) LyX will crash later.
3754 if (from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions)) {
3759 // Do not increase progress when from == to, otherwise the word
3760 // count will be wrong.