]> git.lyx.org Git - lyx.git/blob - src/Buffer.h
Simplify featureAsString()... I don't understand why some people insist
[lyx.git] / src / Buffer.h
1 // -*- C++ -*-
2 /**
3  * \file Buffer.h
4  * This file is part of LyX, the document processor.
5  * Licence details can be found in the file COPYING.
6  *
7  * \author Lars Gullik Bjønnes
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #ifndef BUFFER_H
13 #define BUFFER_H
14
15 #include "OutputEnums.h"
16 #include "update_flags.h"
17
18 #include "insets/InsetCode.h"
19
20 #include "support/strfwd.h"
21 #include "support/types.h"
22
23 #include <list>
24 #include <set>
25 #include <string>
26 #include <vector>
27
28
29 namespace lyx {
30
31 class BiblioInfo;
32 class BufferParams;
33 class BufferSet;
34 class DispatchResult;
35 class DocIterator;
36 class docstring_list;
37 class ErrorList;
38 class FuncRequest;
39 class FuncStatus;
40 class Inset;
41 class InsetRef;
42 class InsetLabel;
43 class Font;
44 class Format;
45 class Lexer;
46 class Text;
47 class LyXVC;
48 class LaTeXFeatures;
49 class Language;
50 class MacroData;
51 class MacroNameSet;
52 class MacroSet;
53 class OutputParams;
54 class Paragraph;
55 class ParConstIterator;
56 class ParIterator;
57 class ParagraphList;
58 class TeXErrors;
59 class TexRow;
60 class TocBackend;
61 class Undo;
62 class WordLangTuple;
63
64 namespace frontend {
65 class GuiBufferDelegate;
66 class WorkAreaManager;
67 }
68
69 namespace support {
70 class FileName;
71 class FileNameList;
72 }
73
74 /** The buffer object.
75  * This is the buffer object. It contains all the informations about
76  * a document loaded into LyX.
77  * The buffer object owns the Text (wrapped in an InsetText), which
78  * contains the individual paragraphs of the document.
79  *
80  *
81  * I am not sure if the class is complete or
82  * minimal, probably not.
83  * \author Lars Gullik Bjønnes
84  */
85 class Buffer {
86 public:
87         /// What type of log will \c getLogName() return?
88         enum LogType {
89                 latexlog, ///< LaTeX log
90                 buildlog  ///< Literate build log
91         };
92
93         /// Result of \c readFile()
94         enum ReadStatus {
95                 failure, ///< The file could not be read
96                 success, ///< The file could not be read
97                 wrongversion ///< The version of the file does not match ours
98         };
99
100
101         /// Method to check if a file is externally modified, used by
102         /// isExternallyModified()
103         /**
104          * timestamp is fast but inaccurate. For example, the granularity
105          * of timestamp on a FAT filesystem is 2 second. Also, various operations
106          * may touch the timestamp of a file even when its content is unchanged.
107          *
108          * checksum is accurate but slow, which can be a problem when it is
109          * frequently used, or used for a large file on a slow (network) file
110          * system.
111          *
112          * FIXME: replace this method with support/FileMonitor.
113          */
114         enum CheckMethod {
115                 checksum_method,  ///< Use file checksum
116                 timestamp_method, ///< Use timestamp, and checksum if timestamp has changed
117         };
118
119         ///
120         enum UpdateScope {
121                 UpdateMaster,
122                 UpdateChildOnly
123         };
124
125         /// Constructor
126         explicit Buffer(std::string const & file, bool readonly = false,
127                 Buffer const * cloned_buffer = 0);
128
129         /// Destructor
130         ~Buffer();
131
132         ///
133         Buffer * clone() const;
134         ///
135         bool isClone() const;
136
137         /** High-level interface to buffer functionality.
138             This function parses a command string and executes it.
139         */
140         void dispatch(std::string const & command, DispatchResult & result);
141
142         /// Maybe we know the function already by number...
143         void dispatch(FuncRequest const & func, DispatchResult & result);
144
145         /// Can this function be exectued?
146         /// \return true if we made a decision
147         bool getStatus(FuncRequest const & cmd, FuncStatus & flag);
148
149         /// read a new document from a string
150         bool readString(std::string const &);
151         /// load a new file
152         bool readFile(support::FileName const & filename);
153
154         /// read the header, returns number of unknown tokens
155         int readHeader(Lexer & lex);
156
157         /** Reads a file without header.
158             \param par if != 0 insert the file.
159             \return \c true if file is not completely read.
160         */
161         bool readDocument(Lexer &);
162
163         ///
164         DocIterator getParFromID(int id) const;
165         /// do we have a paragraph with this id?
166         bool hasParWithID(int id) const;
167
168         ///
169         frontend::WorkAreaManager & workAreaManager() const;
170
171         /** Save file.
172             Takes care of auto-save files and backup file if requested.
173             Returns \c true if the save is successful, \c false otherwise.
174         */
175         bool save() const;
176
177         /// Write document to stream. Returns \c false if unsuccesful.
178         bool write(std::ostream &) const;
179         /// save emergency file
180         /// \return a status message towards the user.
181         docstring emergencyWrite();
182         /// Write file. Returns \c false if unsuccesful.
183         bool writeFile(support::FileName const &) const;
184
185         /// Loads LyX file \c filename into buffer, *  and return success
186         bool loadLyXFile(support::FileName const & s);
187         /// Reloads the LyX file
188         bool reload();
189
190         /// Fill in the ErrorList with the TeXErrors
191         void bufferErrors(TeXErrors const &, ErrorList &) const;
192
193         /// Just a wrapper for writeLaTeXSource, first creating the ofstream.
194         bool makeLaTeXFile(support::FileName const & filename,
195                            std::string const & original_path,
196                            OutputParams const &,
197                            bool output_preamble = true,
198                            bool output_body = true) const;
199         /** Export the buffer to LaTeX.
200             If \p os is a file stream, and params().inputenc is "auto" or
201             "default", and the buffer contains text in different languages
202             with more than one encoding, then this method will change the
203             encoding associated to \p os. Therefore you must not call this
204             method with a string stream if the output is supposed to go to a
205             file. \code
206             ofdocstream ofs;
207             ofs.open("test.tex");
208             writeLaTeXSource(ofs, ...);
209             ofs.close();
210             \endcode is NOT equivalent to \code
211             odocstringstream oss;
212             writeLaTeXSource(oss, ...);
213             ofdocstream ofs;
214             ofs.open("test.tex");
215             ofs << oss.str();
216             ofs.close();
217             \endcode
218          */
219         void writeLaTeXSource(odocstream & os,
220                            std::string const & original_path,
221                            OutputParams const &,
222                            bool output_preamble = true,
223                            bool output_body = true) const;
224         ///
225         void makeDocBookFile(support::FileName const & filename,
226                              OutputParams const & runparams_in,
227                              bool only_body = false) const;
228         ///
229         void writeDocBookSource(odocstream & os, std::string const & filename,
230                              OutputParams const & runparams_in,
231                              bool only_body = false) const;
232         ///
233         void makeLyXHTMLFile(support::FileName const & filename,
234                              OutputParams const & runparams_in,
235                              bool only_body = false) const;
236         ///
237         void writeLyXHTMLSource(odocstream & os,
238                              OutputParams const & runparams_in,
239                              bool only_body = false) const;
240         /// returns the main language for the buffer (document)
241         Language const * language() const;
242         /// get l10n translated to the buffers language
243         docstring const B_(std::string const & l10n) const;
244
245         ///
246         int runChktex();
247         /// return true if the main lyx file does not need saving
248         bool isClean() const;
249         ///
250         bool isDepClean(std::string const & name) const;
251
252         /// whether or not disk file has been externally modified
253         bool isExternallyModified(CheckMethod method) const;
254
255         /// save timestamp and checksum of the given file.
256         void saveCheckSum(support::FileName const & file) const;
257
258         /// mark the main lyx file as not needing saving
259         void markClean() const;
260
261         ///
262         void markDepClean(std::string const & name);
263
264         ///
265         void setUnnamed(bool flag = true);
266
267         /// Whether or not a filename has been assigned to this buffer
268         bool isUnnamed() const;
269
270         /// Whether or not this buffer is internal.
271         ///
272         /// An internal buffer does not contain a real document, but some auxiliary text segment.
273         /// It is not associated with a filename, it is never saved, thus it does not need to be
274         /// automatically saved, nor it needs to trigger any "do you want to save ?" question.
275         bool isInternal() const;
276
277         /// Mark this buffer as dirty.
278         void markDirty();
279
280         /// Returns the buffer's filename. It is always an absolute path.
281         support::FileName fileName() const;
282
283         /// Returns the buffer's filename. It is always an absolute path.
284         std::string absFileName() const;
285
286         /// Returns the the path where the buffer lives.
287         /// It is always an absolute path.
288         std::string filePath() const;
289
290         /** A transformed version of the file name, adequate for LaTeX.
291             \param no_path optional if \c true then the path is stripped.
292         */
293         std::string latexName(bool no_path = true) const;
294
295         /// Get the name and type of the log.
296         std::string logName(LogType * type = 0) const;
297
298         /// Change name of buffer. Updates "read-only" flag.
299         void setFileName(std::string const & newfile);
300
301         /// Set document's parent Buffer.
302         void setParent(Buffer const *);
303         Buffer const * parent() const;
304
305         // Collect all relative buffer
306         std::vector<Buffer const *> allRelatives() const;
307
308         /** Get the document's master (or \c this if this is not a
309             child document)
310          */
311         Buffer const * masterBuffer() const;
312
313         /// \return true if \p child is a child of this \c Buffer.
314         bool isChild(Buffer * child) const;
315         
316         /// return a vector with all children (and grandchildren)
317         std::vector<Buffer *> getChildren(bool grand_children = true) const;
318
319         /// Add all children (and grandchildren) to supplied vector
320         void getChildren(std::vector<Buffer *> & children, bool grand_children = true) const;
321
322         /// Is buffer read-only?
323         bool isReadonly() const;
324
325         /// Set buffer read-only flag
326         void setReadonly(bool flag = true);
327
328         /// returns \c true if the buffer contains a LaTeX document
329         bool isLatex() const;
330         /// returns \c true if the buffer contains a DocBook document
331         bool isDocBook() const;
332         /// returns \c true if the buffer contains a Wed document
333         bool isLiterate() const;
334
335         /** Validate a buffer for LaTeX.
336             This validates the buffer, and returns a struct for use by
337             #makeLaTeX# and others. Its main use is to figure out what
338             commands and packages need to be included in the LaTeX file.
339             It (should) also check that the needed constructs are there
340             (i.e. that the \refs points to coresponding \labels). It
341             should perhaps inset "error" insets to help the user correct
342             obvious mistakes.
343         */
344         void validate(LaTeXFeatures &) const;
345
346         /// Update the list of all bibfiles in use (including bibfiles
347         /// of loaded child documents).
348         void updateBibfilesCache(UpdateScope scope = UpdateMaster) const;
349         /// Return the list with all bibfiles in use (including bibfiles
350         /// of loaded child documents).
351         support::FileNameList const & 
352                 getBibfilesCache(UpdateScope scope = UpdateMaster) const;
353         /// Information from BibTeX databases is cached in the Buffer, so
354         /// we do not have to read the file over and over. 
355         /// Calling this method invalidates the cache and so requires a
356         /// re-read.
357         void invalidateBibinfoCache();
358         /// Updates the cached bibliography information.
359         /// Note that you MUST call this method to update the cache. It will
360         /// not happen otherwise. (Currently, it is called at the start of
361         /// updateLabels() and from GuiCitation.)
362         void checkBibInfoCache() const;
363         /// \return the bibliography information for this buffer's master,
364         /// or just for it, if it isn't a child.
365         BiblioInfo const & masterBibInfo() const;
366         /// \return the bibliography information for this buffer ONLY.
367         BiblioInfo const & localBibInfo() const;
368         ///
369         void getLabelList(std::vector<docstring> &) const;
370
371         ///
372         void changeLanguage(Language const * from, Language const * to);
373
374         ///
375         bool isMultiLingual() const;
376         ///
377         std::set<Language const *> getLanguages() const;
378
379         ///
380         BufferParams & params();
381         BufferParams const & params() const;
382
383         /** The list of paragraphs.
384             This is a linked list of paragraph, this list holds the
385             whole contents of the document.
386          */
387         ParagraphList & paragraphs();
388         ParagraphList const & paragraphs() const;
389
390         /// LyX version control object.
391         LyXVC & lyxvc();
392         LyXVC const & lyxvc() const;
393
394         /// Where to put temporary files.
395         std::string const temppath() const;
396
397         /// Used when typesetting to place errorboxes.
398         TexRow const & texrow() const;
399         TexRow & texrow();
400
401         ///
402         ParIterator par_iterator_begin();
403         ///
404         ParConstIterator par_iterator_begin() const;
405         ///
406         ParIterator par_iterator_end();
407         ///
408         ParConstIterator par_iterator_end() const;
409
410         // Position of the child buffer where it appears first in the master.
411         DocIterator firstChildPosition(Buffer const * child);
412
413         /** \returns true only when the file is fully loaded.
414          *  Used to prevent the premature generation of previews
415          *  and by the citation inset.
416          */
417         bool isFullyLoaded() const;
418         /// Set by buffer_funcs' newFile.
419         void setFullyLoaded(bool);
420
421         /// Our main text (inside the top InsetText)
422         Text & text() const;
423
424         /// Our top InsetText
425         Inset & inset() const;
426
427         //
428         // Macro handling
429         //
430         /// Collect macro definitions in paragraphs
431         void updateMacros() const;
432         /// Iterate through the whole buffer and try to resolve macros
433         void updateMacroInstances() const;
434
435         /// List macro names of this buffer, the parent and the children
436         void listMacroNames(MacroNameSet & macros) const;
437         /// Collect macros of the parent and its children in front of this buffer.
438         void listParentMacros(MacroSet & macros, LaTeXFeatures & features) const;
439
440         /// Return macro defined before pos (or in the master buffer)
441         MacroData const * getMacro(docstring const & name, DocIterator const & pos, bool global = true) const;
442         /// Return macro defined anywhere in the buffer (or in the master buffer)
443         MacroData const * getMacro(docstring const & name, bool global = true) const;
444         /// Return macro defined before the inclusion of the child
445         MacroData const * getMacro(docstring const & name, Buffer const & child, bool global = true) const;
446
447         /// Collect user macro names at loading time
448         typedef std::set<docstring> UserMacroSet;
449         UserMacroSet usermacros;
450
451         /// Replace the inset contents for insets which InsetCode is equal
452         /// to the passed \p inset_code.
453         void changeRefsIfUnique(docstring const & from, docstring const & to,
454                 InsetCode code);
455
456         /// get source code (latex/docbook) for some paragraphs, or all paragraphs
457         /// including preamble
458         void getSourceCode(odocstream & os, pit_type par_begin, pit_type par_end,
459                 bool full_source) const;
460
461         /// Access to error list.
462         /// This method is used only for GUI visualisation of Buffer related
463         /// errors (like parsing or LateX compilation). This method is const
464         /// because modifying the returned ErrorList does not touch the document
465         /// contents.
466         ErrorList & errorList(std::string const & type) const;
467
468         /// The Toc backend.
469         /// This is useful only for screen visualisation of the Buffer. This
470         /// method is const because modifying this backend does not touch
471         /// the document contents.
472         TocBackend & tocBackend() const;
473
474         ///
475         Undo & undo();
476
477         /// This function is called when the buffer is changed.
478         void changed(bool update_metrics) const;
479         ///
480         void setChild(DocIterator const & dit, Buffer * child);
481         ///
482         void updateTocItem(std::string const &, DocIterator const &) const;
483         /// This function is called when the buffer structure is changed.
484         void structureChanged() const;
485         /// This function is called when some parsing error shows up.
486         void errors(std::string const & err, bool from_master = false) const;
487         /// This function is called when the buffer busy status change.
488         void setBusy(bool on) const;
489         /// Update window titles of all users.
490         void updateTitles() const;
491         /// Reset autosave timers for all users.
492         void resetAutosaveTimers() const;
493         ///
494         void message(docstring const & msg) const;
495
496         ///
497         void setGuiDelegate(frontend::GuiBufferDelegate * gui);
498         ///
499         bool hasGuiDelegate() const;
500
501         ///
502         void autoSave() const;
503         ///
504         void removeAutosaveFile() const;
505         ///
506         void moveAutosaveFile(support::FileName const & old) const;
507         ///
508         support::FileName getAutosaveFilename() const;
509
510         /// return the format of the buffer on a string
511         std::string bufferFormat() const;
512         /// return the default output format of the current backend
513         std::string getDefaultOutputFormat() const;
514
515         ///
516         bool doExport(std::string const & format, bool put_in_tempdir,
517                 bool includeall, std::string & result_file) const;
518         ///
519         bool doExport(std::string const & format, bool put_in_tempdir,
520                       bool includeall = false) const;
521         ///
522         bool preview(std::string const & format, bool includeall = false) const;
523         ///
524         bool isExportable(std::string const & format) const;
525         ///
526         std::vector<Format const *> exportableFormats(bool only_viewable) const;
527         ///
528         bool isExportableFormat(std::string const & format) const;
529
530         ///
531         typedef std::vector<std::pair<Inset *, ParIterator> > References;
532         References & references(docstring const & label);
533         References const & references(docstring const & label) const;
534         void clearReferenceCache() const;
535         void setInsetLabel(docstring const & label, InsetLabel const * il);
536         InsetLabel const * insetLabel(docstring const & label) const;
537
538         /// return a list of all used branches (also in children)
539         void getUsedBranches(std::list<docstring> &, bool const from_master = false) const;
540
541         /// sets the buffer_ member for every inset in this buffer.
542         // FIXME This really shouldn't be needed, but at the moment it's not
543         // clear how to do it just for the individual pieces we need.
544         void setBuffersForInsets() const;
545         /// Updates screen labels and some other information associated with
546         /// insets and paragraphs. Actually, it's more like a general "recurse
547         /// through the Buffer" routine, that visits all the insets and paragraphs.
548         void updateLabels() const { updateLabels(UpdateMaster, InternalUpdate); }
549         /// \param scope: whether to start with the master document or just
550         /// do this one.
551         /// \param output: whether we are preparing for output.
552         void updateLabels(UpdateScope scope, UpdateType utype) const;
553         /// 
554         void updateLabels(ParIterator & parit, UpdateType utype) const;
555
556         /// Spellcheck starting from \p from.
557         /// \p from initial position, will then points to the next misspelled
558         ///    word.
559         /// \p to will points to the end of the next misspelled word.
560         /// \p word_lang will contain the found misspelled word.
561         /// \return progress if a new word was found.
562         int spellCheck(DocIterator & from, DocIterator & to,
563                 WordLangTuple & word_lang, docstring_list & suggestions) const;
564
565 private:
566         ///
567         bool readFileHelper(support::FileName const & s);
568         ///
569         std::vector<std::string> backends() const;
570         /** Inserts a file into a document
571             \return \c false if method fails.
572         */
573         ReadStatus readFile(Lexer &, support::FileName const & filename,
574                             bool fromString = false);
575         ///
576         void getLanguages(std::set<Language const *> &) const;
577
578         /// Use the Pimpl idiom to hide the internals.
579         class Impl;
580         /// The pointer never changes although *pimpl_'s contents may.
581         Impl * const d;
582 };
583
584
585 } // namespace lyx
586
587 #endif