4 * This file is part of LyX, the document processor.
5 * Licence details can be found in the file COPYING.
7 * \author Lars Gullik Bjønnes
9 * Full author contact details are available in file CREDITS.
15 #include "OutputEnums.h"
16 #include "OutputParams.h"
18 #include "insets/InsetCode.h"
20 #include "support/strfwd.h"
21 #include "support/types.h"
56 class ParConstIterator;
66 class GuiBufferDelegate;
67 class WorkAreaManager;
81 typedef std::list<Buffer *> ListOfBuffers;
84 /** The buffer object.
85 * This is the buffer object. It contains all the informations about
86 * a document loaded into LyX.
87 * The buffer object owns the Text (wrapped in an InsetText), which
88 * contains the individual paragraphs of the document.
91 * I am not sure if the class is complete or
92 * minimal, probably not.
93 * \author Lars Gullik Bjønnes
97 /// What type of log will \c getLogName() return?
99 latexlog, ///< LaTeX log
100 buildlog ///< Literate build log
103 /// Result of \c readFile()
113 ReadEmergencyFailure,
129 ExportNoPathToFormat,
130 ExportTexPathHasSpaces,
131 ExportConverterError,
137 /// Method to check if a file is externally modified, used by
138 /// isExternallyModified()
140 * timestamp is fast but inaccurate. For example, the granularity
141 * of timestamp on a FAT filesystem is 2 second. Also, various operations
142 * may touch the timestamp of a file even when its content is unchanged.
144 * checksum is accurate but slow, which can be a problem when it is
145 * frequently used, or used for a large file on a slow (network) file
148 * FIXME: replace this method with support/FileMonitor.
151 checksum_method, ///< Use file checksum
152 timestamp_method ///< Use timestamp, and checksum if timestamp has changed
162 explicit Buffer(std::string const & file, bool readonly = false,
163 Buffer const * cloned_buffer = 0);
169 Buffer * clone() const;
171 bool isClone() const;
173 /** High-level interface to buffer functionality.
174 This function parses a command string and executes it.
176 void dispatch(std::string const & command, DispatchResult & result);
178 /// Maybe we know the function already by number...
179 void dispatch(FuncRequest const & func, DispatchResult & result);
181 /// Can this function be exectued?
182 /// \return true if we made a decision
183 bool getStatus(FuncRequest const & cmd, FuncStatus & flag);
186 DocIterator getParFromID(int id) const;
187 /// do we have a paragraph with this id?
188 bool hasParWithID(int id) const;
191 frontend::WorkAreaManager & workAreaManager() const;
194 Takes care of auto-save files and backup file if requested.
195 Returns \c true if the save is successful, \c false otherwise.
198 /// Renames and saves the buffer
199 bool saveAs(support::FileName const & fn);
201 /// Write document to stream. Returns \c false if unsuccessful.
202 bool write(std::ostream &) const;
203 /// Write file. Returns \c false if unsuccessful.
204 bool writeFile(support::FileName const &) const;
206 /// \name Functions involved in reading files/strings.
208 /// Loads the LyX file into the buffer. This function
209 /// tries to extract the file from version control if it
210 /// cannot be found. If it can be found, it will try to
211 /// read an emergency save file or an autosave file.
212 /// \sa loadThisLyXFile
213 ReadStatus loadLyXFile();
214 /// Loads the LyX file \c fn into the buffer. If you want
215 /// to check for files in a version control container,
216 /// emergency or autosave files, one should use \c loadLyXFile.
218 ReadStatus loadThisLyXFile(support::FileName const & fn);
219 /// read a new document from a string
220 bool readString(std::string const &);
221 /// Reloads the LyX file
223 //FIXME: The following function should be private
225 /// read the header, returns number of unknown tokens
226 int readHeader(Lexer & lex);
230 typedef std::map<Buffer const *, Buffer *> BufferMap;
232 void clone(BufferMap &) const;
233 /// save timestamp and checksum of the given file.
234 void saveCheckSum() const;
236 ReadStatus readFile(support::FileName const & fn);
237 /// Reads a file without header.
238 /// \param par if != 0 insert the file.
239 /// \return \c true if file is not completely read.
240 bool readDocument(Lexer &);
241 /// Try to extract the file from a version control container
242 /// before reading if the file cannot be found. This is only
243 /// implemented for RCS.
244 /// \sa LyXVC::file_not_found_hook
245 ReadStatus extractFromVC();
246 /// Reads the first tag of a LyX File and
247 /// returns the file format number.
248 ReadStatus parseLyXFormat(Lexer & lex, support::FileName const & fn,
249 int & file_format) const;
250 /// Convert the LyX file to the LYX_FORMAT using
251 /// the lyx2lyx script and returns the filename
252 /// of the temporary file to be read
253 ReadStatus convertLyXFormat(support::FileName const & fn,
254 support::FileName & tmpfile, int from_format);
258 /// \name Functions involved in autosave and emergency files.
260 /// Save an autosave file to #filename.lyx#
261 bool autoSave() const;
262 /// save emergency file
263 /// \return a status message towards the user.
264 docstring emergencyWrite();
266 //FIXME:The following function should be private
269 void removeAutosaveFile() const;
272 /// Try to load an autosave file associated to \c fn.
273 ReadStatus loadAutosave();
274 /// Try to load an emergency file associated to \c fn.
275 ReadStatus loadEmergency();
276 /// Get the filename of the emergency file associated with the Buffer
277 support::FileName getEmergencyFileName() const;
278 /// Get the filename of the autosave file associated with the Buffer
279 support::FileName getAutosaveFileName() const;
281 void moveAutosaveFile(support::FileName const & old) const;
285 /// Fill in the ErrorList with the TeXErrors
286 void bufferErrors(TeXErrors const &, ErrorList &) const;
295 /// Just a wrapper for writeLaTeXSource, first creating the ofstream.
296 bool makeLaTeXFile(support::FileName const & filename,
297 std::string const & original_path,
298 OutputParams const &,
299 OutputWhat output = FullSource) const;
300 /** Export the buffer to LaTeX.
301 If \p os is a file stream, and params().inputenc is "auto" or
302 "default", and the buffer contains text in different languages
303 with more than one encoding, then this method will change the
304 encoding associated to \p os. Therefore you must not call this
305 method with a string stream if the output is supposed to go to a
308 otexstream os(ofs, texrow);
309 ofs.open("test.tex");
310 writeLaTeXSource(os, ...);
312 \endcode is NOT equivalent to \code
313 odocstringstream oss;
314 otexstream os(oss, texrow);
315 writeLaTeXSource(os, ...);
317 ofs.open("test.tex");
322 void writeLaTeXSource(otexstream & os,
323 std::string const & original_path,
324 OutputParams const &,
325 OutputWhat output = FullSource) const;
327 void makeDocBookFile(support::FileName const & filename,
328 OutputParams const & runparams_in,
329 OutputWhat output = FullSource) const;
331 void writeDocBookSource(odocstream & os, std::string const & filename,
332 OutputParams const & runparams_in,
333 OutputWhat output = FullSource) const;
335 void makeLyXHTMLFile(support::FileName const & filename,
336 OutputParams const & runparams_in) const;
338 void writeLyXHTMLSource(odocstream & os,
339 OutputParams const & runparams_in,
340 OutputWhat output = FullSource) const;
341 /// returns the main language for the buffer (document)
342 Language const * language() const;
343 /// get l10n translated to the buffers language
344 docstring const B_(std::string const & l10n) const;
348 /// return true if the main lyx file does not need saving
349 bool isClean() const;
351 bool isDepClean(std::string const & name) const;
353 /// whether or not disk file has been externally modified
354 bool isExternallyModified(CheckMethod method) const;
356 /// mark the main lyx file as not needing saving
357 void markClean() const;
360 void markDepClean(std::string const & name);
363 void setUnnamed(bool flag = true);
365 /// Whether or not a filename has been assigned to this buffer
366 bool isUnnamed() const;
368 /// Whether or not this buffer is internal.
370 /// An internal buffer does not contain a real document, but some auxiliary text segment.
371 /// It is not associated with a filename, it is never saved, thus it does not need to be
372 /// automatically saved, nor it needs to trigger any "do you want to save ?" question.
373 bool isInternal() const;
375 /// Mark this buffer as dirty.
378 /// Returns the buffer's filename. It is always an absolute path.
379 support::FileName fileName() const;
381 /// Returns the buffer's filename. It is always an absolute path.
382 std::string absFileName() const;
384 /// Returns the the path where the buffer lives.
385 /// It is always an absolute path.
386 std::string filePath() const;
388 /** A transformed version of the file name, adequate for LaTeX.
389 \param no_path optional if \c true then the path is stripped.
391 std::string latexName(bool no_path = true) const;
393 /// Get the name and type of the log.
394 std::string logName(LogType * type = 0) const;
396 /// Set document's parent Buffer.
397 void setParent(Buffer const *);
398 Buffer const * parent() const;
400 /** Get the document's master (or \c this if this is not a
403 Buffer const * masterBuffer() const;
405 /// \return true if \p child is a child of this \c Buffer.
406 bool isChild(Buffer * child) const;
408 /// \return true if this \c Buffer has children
409 bool hasChildren() const;
411 /// \return a list of the direct children of this Buffer.
412 /// this list has no duplicates and is in the order in which
413 /// the children appear.
414 ListOfBuffers getChildren() const;
416 /// \return a list of all descendents of this Buffer (children,
417 /// grandchildren, etc). this list has no duplicates and is in
418 /// the order in which the children appear.
419 ListOfBuffers getDescendents() const;
421 /// Collect all relative buffers, in the order in which they appear.
422 /// I.e., the "root" Buffer is first, then its first child, then any
423 /// of its children, etc. However, there are no duplicates in this
425 /// This is "stable", too, in the sense that it returns the same
426 /// thing from whichever Buffer it is called.
427 ListOfBuffers allRelatives() const;
429 /// Is buffer read-only?
430 bool isReadonly() const;
432 /// Set buffer read-only flag
433 void setReadonly(bool flag = true);
435 /** Validate a buffer for LaTeX.
436 This validates the buffer, and returns a struct for use by
437 #makeLaTeX# and others. Its main use is to figure out what
438 commands and packages need to be included in the LaTeX file.
439 It (should) also check that the needed constructs are there
440 (i.e. that the \refs points to coresponding \labels). It
441 should perhaps inset "error" insets to help the user correct
444 void validate(LaTeXFeatures &) const;
446 /// Reference information is cached in the Buffer, so we do not
447 /// have to check or read things over and over.
449 /// There are two caches.
451 /// One is a cache of the BibTeX files from which reference info is
452 /// being gathered. This cache is PER BUFFER, and the cache for the
453 /// master essentially includes the cache for its children. This gets
454 /// invalidated when an InsetBibtex is created, deleted, or modified.
456 /// The other is a cache of the reference information itself. This
457 /// exists only in the master buffer, and when it needs to be updated,
458 /// the children add their information to the master's cache.
460 /// Calling this method invalidates the cache and so requires a
462 void invalidateBibinfoCache() const;
463 /// This invalidates the cache of files we need to check.
464 void invalidateBibfileCache() const;
465 /// Updates the cached bibliography information, checking first to see
466 /// whether the cache is valid. If so, we do nothing. If not, then we
467 /// reload all the BibTeX info.
468 /// Note that this operates on the master document.
469 void reloadBibInfoCache() const;
470 /// \return the bibliography information for this buffer's master,
471 /// or just for it, if it isn't a child.
472 BiblioInfo const & masterBibInfo() const;
473 /// collect bibliography info from the various insets in this buffer.
474 void collectBibKeys() const;
475 /// add some BiblioInfo to our cache
476 void addBiblioInfo(BiblioInfo const & bi) const;
477 /// add a single piece of bibliography info to our cache
478 void addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const;
480 bool citeLabelsValid() const;
482 void getLabelList(std::vector<docstring> &) const;
485 void changeLanguage(Language const * from, Language const * to);
488 bool isMultiLingual() const;
490 std::set<Language const *> getLanguages() const;
493 BufferParams & params();
494 BufferParams const & params() const;
496 /** The list of paragraphs.
497 This is a linked list of paragraph, this list holds the
498 whole contents of the document.
500 ParagraphList & paragraphs();
501 ParagraphList const & paragraphs() const;
503 /// LyX version control object.
505 LyXVC const & lyxvc() const;
507 /// Where to put temporary files.
508 std::string const temppath() const;
510 /// Used when typesetting to place errorboxes.
511 TexRow const & texrow() const;
515 ParIterator par_iterator_begin();
517 ParConstIterator par_iterator_begin() const;
519 ParIterator par_iterator_end();
521 ParConstIterator par_iterator_end() const;
523 // Position of the child buffer where it appears first in the master.
524 DocIterator firstChildPosition(Buffer const * child);
526 /** \returns true only when the file is fully loaded.
527 * Used to prevent the premature generation of previews
528 * and by the citation inset.
530 bool isFullyLoaded() const;
531 /// Set by buffer_funcs' newFile.
532 void setFullyLoaded(bool);
534 /// FIXME: Needed by RenderPreview.
535 graphics::PreviewLoader * loader() const;
536 /// Update the LaTeX preview snippets associated with this buffer
537 void updatePreviews() const;
538 /// Remove any previewed LaTeX snippets associated with this buffer
539 void removePreviews() const;
541 /// Our main text (inside the top InsetText)
544 /// Our top InsetText
545 Inset & inset() const;
550 /// Collect macro definitions in paragraphs
551 void updateMacros() const;
552 /// Iterate through the whole buffer and try to resolve macros
553 void updateMacroInstances(UpdateType) const;
555 /// List macro names of this buffer, the parent and the children
556 void listMacroNames(MacroNameSet & macros) const;
557 /// Collect macros of the parent and its children in front of this buffer.
558 void listParentMacros(MacroSet & macros, LaTeXFeatures & features) const;
560 /// Return macro defined before pos (or in the master buffer)
561 MacroData const * getMacro(docstring const & name, DocIterator const & pos, bool global = true) const;
562 /// Return macro defined anywhere in the buffer (or in the master buffer)
563 MacroData const * getMacro(docstring const & name, bool global = true) const;
564 /// Return macro defined before the inclusion of the child
565 MacroData const * getMacro(docstring const & name, Buffer const & child, bool global = true) const;
567 /// Collect user macro names at loading time
568 typedef std::set<docstring> UserMacroSet;
569 mutable UserMacroSet usermacros;
571 /// Replace the inset contents for insets which InsetCode is equal
572 /// to the passed \p inset_code.
573 void changeRefsIfUnique(docstring const & from, docstring const & to,
576 /// get source code (latex/docbook) for some paragraphs, or all paragraphs
577 /// including preamble
578 void getSourceCode(odocstream & os, std::string const format,
579 pit_type par_begin, pit_type par_end, OutputWhat output) const;
581 /// Access to error list.
582 /// This method is used only for GUI visualisation of Buffer related
583 /// errors (like parsing or LateX compilation). This method is const
584 /// because modifying the returned ErrorList does not touch the document
586 ErrorList & errorList(std::string const & type) const;
589 /// This is useful only for screen visualisation of the Buffer. This
590 /// method is const because modifying this backend does not touch
591 /// the document contents.
592 TocBackend & tocBackend() const;
597 /// This function is called when the buffer is changed.
598 void changed(bool update_metrics) const;
600 void setChild(DocIterator const & dit, Buffer * child);
602 void updateTocItem(std::string const &, DocIterator const &) const;
603 /// This function is called when the buffer structure is changed.
604 void structureChanged() const;
605 /// This function is called when some parsing error shows up.
606 void errors(std::string const & err, bool from_master = false) const;
607 /// This function is called when the buffer busy status change.
608 void setBusy(bool on) const;
609 /// Update window titles of all users.
610 void updateTitles() const;
611 /// Reset autosave timers for all users.
612 void resetAutosaveTimers() const;
614 void message(docstring const & msg) const;
617 void setGuiDelegate(frontend::GuiBufferDelegate * gui);
619 bool hasGuiDelegate() const;
622 ExportStatus doExport(std::string const & target, bool put_in_tempdir) const;
624 ExportStatus doExport(std::string const & target, bool put_in_tempdir,
625 std::string & result_file) const;
627 ExportStatus preview(std::string const & format) const;
630 /// target is a format name optionally followed by a space
631 /// and a destination file-name
632 ExportStatus doExport(std::string const & target, bool put_in_tempdir,
633 bool includeall, std::string & result_file) const;
635 ExportStatus doExport(std::string const & target, bool put_in_tempdir,
636 bool includeall) const;
638 ExportStatus preview(std::string const & format, bool includeall = false) const;
642 bool isExporting() const;
645 typedef std::vector<std::pair<Inset *, ParIterator> > References;
646 References & references(docstring const & label);
647 References const & references(docstring const & label) const;
648 void clearReferenceCache() const;
649 void setInsetLabel(docstring const & label, InsetLabel const * il);
650 InsetLabel const * insetLabel(docstring const & label) const;
652 /// return a list of all used branches (also in children)
653 void getUsedBranches(std::list<docstring> &, bool const from_master = false) const;
655 /// sets the buffer_ member for every inset in this buffer.
656 // FIXME This really shouldn't be needed, but at the moment it's not
657 // clear how to do it just for the individual pieces we need.
658 void setBuffersForInsets() const;
659 /// Updates screen labels and some other information associated with
660 /// insets and paragraphs. Actually, it's more like a general "recurse
661 /// through the Buffer" routine, that visits all the insets and paragraphs.
662 void updateBuffer() const { updateBuffer(UpdateMaster, InternalUpdate); }
663 /// \param scope: whether to start with the master document or just
665 /// \param output: whether we are preparing for output.
666 void updateBuffer(UpdateScope scope, UpdateType utype) const;
668 void updateBuffer(ParIterator & parit, UpdateType utype) const;
670 /// Spellcheck starting from \p from.
671 /// \p from initial position, will then points to the next misspelled
673 /// \p to will points to the end of the next misspelled word.
674 /// \p word_lang will contain the found misspelled word.
675 /// \return progress if a new word was found.
676 int spellCheck(DocIterator & from, DocIterator & to,
677 WordLangTuple & word_lang, docstring_list & suggestions) const;
679 void checkChildBuffers();
682 class MarkAsExporting;
683 friend class MarkAsExporting;
684 /// mark the buffer as busy exporting something, or not
685 void setExportStatus(bool e) const;
687 /// Change name of buffer. Updates "read-only" flag.
688 void setFileName(support::FileName const & fname);
690 void getLanguages(std::set<Language const *> &) const;
691 /// Checks whether any of the referenced bibfiles have changed since the
692 /// last time we loaded the cache. Note that this does NOT update the
693 /// cached information.
694 void checkIfBibInfoCacheIsValid() const;
695 /// Update the list of all bibfiles in use (including bibfiles
696 /// of loaded child documents).
697 void updateBibfilesCache(UpdateScope scope = UpdateMaster) const;
698 /// Return the list with all bibfiles in use (including bibfiles
699 /// of loaded child documents).
700 support::FileNameList const &
701 getBibfilesCache(UpdateScope scope = UpdateMaster) const;
703 void collectChildren(ListOfBuffers & children, bool grand_children) const;
706 Buffer(Buffer const &);
707 void operator=(Buffer const &);
709 /// Use the Pimpl idiom to hide the internals.
711 /// The pointer never changes although *pimpl_'s contents may.