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,
130 ExportNoPathToFormat,
131 ExportTexPathHasSpaces,
132 ExportConverterError,
138 /// Method to check if a file is externally modified, used by
139 /// isExternallyModified()
141 * timestamp is fast but inaccurate. For example, the granularity
142 * of timestamp on a FAT filesystem is 2 second. Also, various operations
143 * may touch the timestamp of a file even when its content is unchanged.
145 * checksum is accurate but slow, which can be a problem when it is
146 * frequently used, or used for a large file on a slow (network) file
149 * FIXME: replace this method with support/FileMonitor.
152 checksum_method, ///< Use file checksum
153 timestamp_method ///< Use timestamp, and checksum if timestamp has changed
163 explicit Buffer(std::string const & file, bool readonly = false,
164 Buffer const * cloned_buffer = 0);
170 Buffer * clone() const;
172 bool isClone() const;
174 /** High-level interface to buffer functionality.
175 This function parses a command string and executes it.
177 void dispatch(std::string const & command, DispatchResult & result);
179 /// Maybe we know the function already by number...
180 void dispatch(FuncRequest const & func, DispatchResult & result);
182 /// Can this function be exectued?
183 /// \return true if we made a decision
184 bool getStatus(FuncRequest const & cmd, FuncStatus & flag);
187 DocIterator getParFromID(int id) const;
188 /// do we have a paragraph with this id?
189 bool hasParWithID(int id) const;
192 frontend::WorkAreaManager & workAreaManager() const;
195 Takes care of auto-save files and backup file if requested.
196 Returns \c true if the save is successful, \c false otherwise.
199 /// Renames and saves the buffer
200 bool saveAs(support::FileName const & fn);
202 /// Write document to stream. Returns \c false if unsuccessful.
203 bool write(std::ostream &) const;
204 /// Write file. Returns \c false if unsuccessful.
205 bool writeFile(support::FileName const &) const;
207 /// \name Functions involved in reading files/strings.
209 /// Loads the LyX file into the buffer. This function
210 /// tries to extract the file from version control if it
211 /// cannot be found. If it can be found, it will try to
212 /// read an emergency save file or an autosave file.
213 /// \sa loadThisLyXFile
214 ReadStatus loadLyXFile();
215 /// Loads the LyX file \c fn into the buffer. If you want
216 /// to check for files in a version control container,
217 /// emergency or autosave files, one should use \c loadLyXFile.
219 ReadStatus loadThisLyXFile(support::FileName const & fn);
220 /// read a new document from a string
221 bool readString(std::string const &);
222 /// Reloads the LyX file
224 //FIXME: The following function should be private
226 /// read the header, returns number of unknown tokens
227 int readHeader(Lexer & lex);
231 typedef std::map<Buffer const *, Buffer *> BufferMap;
233 void clone(BufferMap &) const;
234 /// save timestamp and checksum of the given file.
235 void saveCheckSum() const;
237 ReadStatus readFile(support::FileName const & fn);
238 /// Reads a file without header.
239 /// \param par if != 0 insert the file.
240 /// \return \c true if file is not completely read.
241 bool readDocument(Lexer &);
242 /// Try to extract the file from a version control container
243 /// before reading if the file cannot be found. This is only
244 /// implemented for RCS.
245 /// \sa LyXVC::file_not_found_hook
246 ReadStatus extractFromVC();
247 /// Reads the first tag of a LyX File and
248 /// returns the file format number.
249 ReadStatus parseLyXFormat(Lexer & lex, support::FileName const & fn,
250 int & file_format) const;
251 /// Convert the LyX file to the LYX_FORMAT using
252 /// the lyx2lyx script and returns the filename
253 /// of the temporary file to be read
254 ReadStatus convertLyXFormat(support::FileName const & fn,
255 support::FileName & tmpfile, int from_format);
259 /// \name Functions involved in autosave and emergency files.
261 /// Save an autosave file to #filename.lyx#
262 bool autoSave() const;
263 /// save emergency file
264 /// \return a status message towards the user.
265 docstring emergencyWrite();
267 //FIXME:The following function should be private
270 void removeAutosaveFile() const;
273 /// Try to load an autosave file associated to \c fn.
274 ReadStatus loadAutosave();
275 /// Try to load an emergency file associated to \c fn.
276 ReadStatus loadEmergency();
277 /// Get the filename of the emergency file associated with the Buffer
278 support::FileName getEmergencyFileName() const;
279 /// Get the filename of the autosave file associated with the Buffer
280 support::FileName getAutosaveFileName() const;
282 void moveAutosaveFile(support::FileName const & old) const;
286 /// Fill in the ErrorList with the TeXErrors
287 void bufferErrors(TeXErrors const &, ErrorList &) const;
296 /// Just a wrapper for writeLaTeXSource, first creating the ofstream.
297 bool makeLaTeXFile(support::FileName const & filename,
298 std::string const & original_path,
299 OutputParams const &,
300 OutputWhat output = FullSource) const;
301 /** Export the buffer to LaTeX.
302 If \p os is a file stream, and params().inputenc is "auto" or
303 "default", and the buffer contains text in different languages
304 with more than one encoding, then this method will change the
305 encoding associated to \p os. Therefore you must not call this
306 method with a string stream if the output is supposed to go to a
309 otexstream os(ofs, texrow);
310 ofs.open("test.tex");
311 writeLaTeXSource(os, ...);
313 \endcode is NOT equivalent to \code
314 odocstringstream oss;
315 otexstream os(oss, texrow);
316 writeLaTeXSource(os, ...);
318 ofs.open("test.tex");
323 void writeLaTeXSource(otexstream & os,
324 std::string const & original_path,
325 OutputParams const &,
326 OutputWhat output = FullSource) const;
328 void makeDocBookFile(support::FileName const & filename,
329 OutputParams const & runparams_in,
330 OutputWhat output = FullSource) const;
332 void writeDocBookSource(odocstream & os, std::string const & filename,
333 OutputParams const & runparams_in,
334 OutputWhat output = FullSource) const;
336 void makeLyXHTMLFile(support::FileName const & filename,
337 OutputParams const & runparams_in) const;
339 void writeLyXHTMLSource(odocstream & os,
340 OutputParams const & runparams_in,
341 OutputWhat output = FullSource) const;
342 /// returns the main language for the buffer (document)
343 Language const * language() const;
344 /// get l10n translated to the buffers language
345 docstring const B_(std::string const & l10n) const;
349 /// return true if the main lyx file does not need saving
350 bool isClean() const;
352 bool isDepClean(std::string const & name) const;
354 /// whether or not disk file has been externally modified
355 bool isExternallyModified(CheckMethod method) const;
357 /// mark the main lyx file as not needing saving
358 void markClean() const;
361 void markDepClean(std::string const & name);
364 void setUnnamed(bool flag = true);
366 /// Whether or not a filename has been assigned to this buffer
367 bool isUnnamed() const;
369 /// Whether or not this buffer is internal.
371 /// An internal buffer does not contain a real document, but some auxiliary text segment.
372 /// It is not associated with a filename, it is never saved, thus it does not need to be
373 /// automatically saved, nor it needs to trigger any "do you want to save ?" question.
374 bool isInternal() const;
376 /// Mark this buffer as dirty.
379 /// Returns the buffer's filename. It is always an absolute path.
380 support::FileName fileName() const;
382 /// Returns the buffer's filename. It is always an absolute path.
383 std::string absFileName() const;
385 /// Returns the the path where the buffer lives.
386 /// It is always an absolute path.
387 std::string filePath() const;
389 /** A transformed version of the file name, adequate for LaTeX.
390 \param no_path optional if \c true then the path is stripped.
392 std::string latexName(bool no_path = true) const;
394 /// Get the name and type of the log.
395 std::string logName(LogType * type = 0) const;
397 /// Set document's parent Buffer.
398 void setParent(Buffer const *);
399 Buffer const * parent() const;
401 /** Get the document's master (or \c this if this is not a
404 Buffer const * masterBuffer() const;
406 /// \return true if \p child is a child of this \c Buffer.
407 bool isChild(Buffer * child) const;
409 /// \return true if this \c Buffer has children
410 bool hasChildren() const;
412 /// \return a list of the direct children of this Buffer.
413 /// this list has no duplicates and is in the order in which
414 /// the children appear.
415 ListOfBuffers getChildren() const;
417 /// \return a list of all descendents of this Buffer (children,
418 /// grandchildren, etc). this list has no duplicates and is in
419 /// the order in which the children appear.
420 ListOfBuffers getDescendents() const;
422 /// Collect all relative buffers, in the order in which they appear.
423 /// I.e., the "root" Buffer is first, then its first child, then any
424 /// of its children, etc. However, there are no duplicates in this
426 /// This is "stable", too, in the sense that it returns the same
427 /// thing from whichever Buffer it is called.
428 ListOfBuffers allRelatives() const;
430 /// Is buffer read-only?
431 bool isReadonly() const;
433 /// Set buffer read-only flag
434 void setReadonly(bool flag = true);
436 /** Validate a buffer for LaTeX.
437 This validates the buffer, and returns a struct for use by
438 #makeLaTeX# and others. Its main use is to figure out what
439 commands and packages need to be included in the LaTeX file.
440 It (should) also check that the needed constructs are there
441 (i.e. that the \refs points to coresponding \labels). It
442 should perhaps inset "error" insets to help the user correct
445 void validate(LaTeXFeatures &) const;
447 /// Reference information is cached in the Buffer, so we do not
448 /// have to check or read things over and over.
450 /// There are two caches.
452 /// One is a cache of the BibTeX files from which reference info is
453 /// being gathered. This cache is PER BUFFER, and the cache for the
454 /// master essentially includes the cache for its children. This gets
455 /// invalidated when an InsetBibtex is created, deleted, or modified.
457 /// The other is a cache of the reference information itself. This
458 /// exists only in the master buffer, and when it needs to be updated,
459 /// the children add their information to the master's cache.
461 /// Calling this method invalidates the cache and so requires a
463 void invalidateBibinfoCache() const;
464 /// This invalidates the cache of files we need to check.
465 void invalidateBibfileCache() const;
466 /// Updates the cached bibliography information, checking first to see
467 /// whether the cache is valid. If so, we do nothing. If not, then we
468 /// reload all the BibTeX info.
469 /// Note that this operates on the master document.
470 void reloadBibInfoCache() const;
471 /// \return the bibliography information for this buffer's master,
472 /// or just for it, if it isn't a child.
473 BiblioInfo const & masterBibInfo() const;
474 /// collect bibliography info from the various insets in this buffer.
475 void collectBibKeys() const;
476 /// add some BiblioInfo to our cache
477 void addBiblioInfo(BiblioInfo const & bi) const;
478 /// add a single piece of bibliography info to our cache
479 void addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const;
481 bool citeLabelsValid() const;
483 void getLabelList(std::vector<docstring> &) const;
486 void changeLanguage(Language const * from, Language const * to);
489 bool isMultiLingual() const;
491 std::set<Language const *> getLanguages() const;
494 BufferParams & params();
495 BufferParams const & params() const;
497 /** The list of paragraphs.
498 This is a linked list of paragraph, this list holds the
499 whole contents of the document.
501 ParagraphList & paragraphs();
502 ParagraphList const & paragraphs() const;
504 /// LyX version control object.
506 LyXVC const & lyxvc() const;
508 /// Where to put temporary files.
509 std::string const temppath() const;
511 /// Used when typesetting to place errorboxes.
512 TexRow const & texrow() const;
516 ParIterator par_iterator_begin();
518 ParConstIterator par_iterator_begin() const;
520 ParIterator par_iterator_end();
522 ParConstIterator par_iterator_end() const;
524 // Position of the child buffer where it appears first in the master.
525 DocIterator firstChildPosition(Buffer const * child);
527 /** \returns true only when the file is fully loaded.
528 * Used to prevent the premature generation of previews
529 * and by the citation inset.
531 bool isFullyLoaded() const;
532 /// Set by buffer_funcs' newFile.
533 void setFullyLoaded(bool);
535 /// FIXME: Needed by RenderPreview.
536 graphics::PreviewLoader * loader() const;
537 /// Update the LaTeX preview snippets associated with this buffer
538 void updatePreviews() const;
539 /// Remove any previewed LaTeX snippets associated with this buffer
540 void removePreviews() const;
542 /// Our main text (inside the top InsetText)
545 /// Our top InsetText
546 Inset & inset() const;
551 /// Collect macro definitions in paragraphs
552 void updateMacros() const;
553 /// Iterate through the whole buffer and try to resolve macros
554 void updateMacroInstances(UpdateType) const;
556 /// List macro names of this buffer, the parent and the children
557 void listMacroNames(MacroNameSet & macros) const;
558 /// Collect macros of the parent and its children in front of this buffer.
559 void listParentMacros(MacroSet & macros, LaTeXFeatures & features) const;
561 /// Return macro defined before pos (or in the master buffer)
562 MacroData const * getMacro(docstring const & name, DocIterator const & pos, bool global = true) const;
563 /// Return macro defined anywhere in the buffer (or in the master buffer)
564 MacroData const * getMacro(docstring const & name, bool global = true) const;
565 /// Return macro defined before the inclusion of the child
566 MacroData const * getMacro(docstring const & name, Buffer const & child, bool global = true) const;
568 /// Collect user macro names at loading time
569 typedef std::set<docstring> UserMacroSet;
570 mutable UserMacroSet usermacros;
572 /// Replace the inset contents for insets which InsetCode is equal
573 /// to the passed \p inset_code.
574 void changeRefsIfUnique(docstring const & from, docstring const & to,
577 /// get source code (latex/docbook) for some paragraphs, or all paragraphs
578 /// including preamble
579 void getSourceCode(odocstream & os, std::string const format,
580 pit_type par_begin, pit_type par_end, OutputWhat output) const;
582 /// Access to error list.
583 /// This method is used only for GUI visualisation of Buffer related
584 /// errors (like parsing or LateX compilation). This method is const
585 /// because modifying the returned ErrorList does not touch the document
587 ErrorList & errorList(std::string const & type) const;
590 /// This is useful only for screen visualisation of the Buffer. This
591 /// method is const because modifying this backend does not touch
592 /// the document contents.
593 TocBackend & tocBackend() const;
598 /// This function is called when the buffer is changed.
599 void changed(bool update_metrics) const;
601 void setChild(DocIterator const & dit, Buffer * child);
603 void updateTocItem(std::string const &, DocIterator const &) const;
604 /// This function is called when the buffer structure is changed.
605 void structureChanged() const;
606 /// This function is called when some parsing error shows up.
607 void errors(std::string const & err, bool from_master = false) const;
608 /// This function is called when the buffer busy status change.
609 void setBusy(bool on) const;
610 /// Update window titles of all users.
611 void updateTitles() const;
612 /// Reset autosave timers for all users.
613 void resetAutosaveTimers() const;
615 void message(docstring const & msg) const;
618 void setGuiDelegate(frontend::GuiBufferDelegate * gui);
620 bool hasGuiDelegate() const;
623 ExportStatus doExport(std::string const & target, bool put_in_tempdir) const;
625 ExportStatus doExport(std::string const & target, bool put_in_tempdir,
626 std::string & result_file) const;
628 ExportStatus preview(std::string const & format) const;
631 /// target is a format name optionally followed by a space
632 /// and a destination file-name
633 ExportStatus doExport(std::string const & target, bool put_in_tempdir,
634 bool includeall, std::string & result_file) const;
636 ExportStatus doExport(std::string const & target, bool put_in_tempdir,
637 bool includeall) const;
639 ExportStatus preview(std::string const & format, bool includeall = false) const;
643 bool isExporting() const;
646 typedef std::vector<std::pair<Inset *, ParIterator> > References;
647 References & references(docstring const & label);
648 References const & references(docstring const & label) const;
649 void clearReferenceCache() const;
650 void setInsetLabel(docstring const & label, InsetLabel const * il);
651 InsetLabel const * insetLabel(docstring const & label) const;
653 /// return a list of all used branches (also in children)
654 void getUsedBranches(std::list<docstring> &, bool const from_master = false) const;
656 /// sets the buffer_ member for every inset in this buffer.
657 // FIXME This really shouldn't be needed, but at the moment it's not
658 // clear how to do it just for the individual pieces we need.
659 void setBuffersForInsets() const;
660 /// Updates screen labels and some other information associated with
661 /// insets and paragraphs. Actually, it's more like a general "recurse
662 /// through the Buffer" routine, that visits all the insets and paragraphs.
663 void updateBuffer() const { updateBuffer(UpdateMaster, InternalUpdate); }
664 /// \param scope: whether to start with the master document or just
666 /// \param output: whether we are preparing for output.
667 void updateBuffer(UpdateScope scope, UpdateType utype) const;
669 void updateBuffer(ParIterator & parit, UpdateType utype) const;
671 /// Spellcheck starting from \p from.
672 /// \p from initial position, will then points to the next misspelled
674 /// \p to will points to the end of the next misspelled word.
675 /// \p word_lang will contain the found misspelled word.
676 /// \return progress if a new word was found.
677 int spellCheck(DocIterator & from, DocIterator & to,
678 WordLangTuple & word_lang, docstring_list & suggestions) const;
680 void checkChildBuffers();
683 class MarkAsExporting;
684 friend class MarkAsExporting;
685 /// mark the buffer as busy exporting something, or not
686 void setExportStatus(bool e) const;
688 /// Change name of buffer. Updates "read-only" flag.
689 void setFileName(support::FileName const & fname);
691 void getLanguages(std::set<Language const *> &) const;
692 /// Checks whether any of the referenced bibfiles have changed since the
693 /// last time we loaded the cache. Note that this does NOT update the
694 /// cached information.
695 void checkIfBibInfoCacheIsValid() const;
696 /// Update the list of all bibfiles in use (including bibfiles
697 /// of loaded child documents).
698 void updateBibfilesCache(UpdateScope scope = UpdateMaster) const;
699 /// Return the list with all bibfiles in use (including bibfiles
700 /// of loaded child documents).
701 support::FileNameList const &
702 getBibfilesCache(UpdateScope scope = UpdateMaster) const;
704 void collectChildren(ListOfBuffers & children, bool grand_children) const;
707 Buffer(Buffer const &);
708 void operator=(Buffer const &);
710 /// Use the Pimpl idiom to hide the internals.
712 /// The pointer never changes although *pimpl_'s contents may.