evennia.commands.default.help

The help command. The basic idea is that help texts for commands are best written by those that write the commands - the developers. So command-help is all auto-loaded and searched from the current command set. The normal, database-tied help system is used for collaborative creation of other help topics such as RP help or game-world aides. Help entries can also be created outside the game in modules given by **settings.FILE_HELP_ENTRY_MODULES**.

class evennia.commands.default.help.CmdHelp(**kwargs)[source]

Bases: MuxCommand

Get help.

Usage:

help help <topic, command or category> help <topic>/<subtopic> help <topic>/<subtopic>/<subsubtopic> …

Use the ‘help’ command alone to see an index of all help topics, organized by category. Some big topics may offer additional sub-topics.

key = 'help'
aliases = ['?']
locks = 'cmd:all()'
arg_regex = re.compile('\\s|$', re.IGNORECASE)
return_cmdset = True
help_more = True
index_type_separator_clr = '|w'
index_category_clr = '|W'
index_topic_clr = '|G'
suggestion_cutoff = 0.6
suggestion_maxnum = 5
subtopic_separator_char = '/'
clickable_topics = True
msg_help(text, **kwargs)[source]

messages text to the caller, adding an extra oob argument to indicate that this is a help command result and could be rendered in a separate help window.

format_help_entry(topic='', help_text='', aliases=None, suggested=None, subtopics=None, click_topics=True)[source]

This visually formats the help entry. This method can be overridden to customize the way a help entry is displayed.

Parameters:
  • title (str, optional) – The title of the help entry.

  • help_text (str, optional) – Text of the help entry.

  • aliases (list, optional) – List of help-aliases (displayed in header).

  • suggested (list, optional) – Strings suggested reading (based on title).

  • subtopics (list, optional) – A list of strings - the subcategories available for this entry.

  • click_topics (bool, optional) – Should help topics be clickable. Default is True.

Returns:

help_message (str) – Help entry formated for console.

format_help_index(cmd_help_dict=None, db_help_dict=None, title_lone_category=False, click_topics=True)[source]

Output a category-ordered g for displaying the main help, grouped by category.

Parameters:
  • cmd_help_dict (dict) – A dict {“category”: [topic, topic, …]} for command-based help.

  • db_help_dict (dict) – A dict {“category”: [topic, topic], …]} for database-based help.

  • title_lone_category (bool, optional) – If a lone category should be titled with the category name or not. While pointless in a general index, the title should probably show when explicitly listing the category itself.

  • click_topics (bool, optional) – If help-topics are clickable or not (for webclient or telnet clients with MXP support).

Returns:

str – The help index organized into a grid.

Notes

The input are the pre-loaded help files for commands and database-helpfiles respectively. You can override this method to return a custom display of the list of commands and topics.

can_read_topic(cmd_or_topic, caller)[source]

Helper method. If this return True, the given help topic be viewable in the help listing. Note that even if this returns False, the entry will still be visible in the help index unless should_list_topic is also returning False.

Parameters:
Returns:

bool – If command can be viewed or not.

Notes

This uses the ‘read’ lock. If no ‘read’ lock is defined, the topic is assumed readable by all.

can_list_topic(cmd_or_topic, caller)[source]

Should the specified command appear in the help table?

This method only checks whether a specified command should appear in the table of topics/commands. The command can be used by the caller (see the ‘should_show_help’ method) and the command will still be available, for instance, if a character type ‘help name of the command’. However, if you return False, the specified command will not appear in the table. This is sometimes useful to “hide” commands in the table, but still access them through the help system.

Parameters:
Returns:

bool – If command should be listed or not.

Notes

The .auto_help propery is checked for commands. For all help entries, the ‘view’ lock will be checked, and if no such lock is defined, the ‘read’ lock will be used. If neither lock is defined, the help entry is assumed to be accessible to all.

collect_topics(caller, mode='list')[source]

Collect help topics from all sources (cmd/db/file).

Parameters:
  • caller (Object or Account) – The user of the Command.

  • mode (str) – One of ‘list’ or ‘query’, where the first means we are collecting to view the help index and the second because of wanting to search for a specific help entry/cmd to read. This determines which access should be checked.

Returns:

tuple – A tuple of three dicts containing the different types of help entries in the order cmd-help, db-help, file-help:

({key: cmd,…}, {key: dbentry,…}, {key: fileentry,…}

Perform a help-query search, default using Lunr search engine.

Parameters:
  • query (str) – The help entry to search for.

  • entries (list) – All possibilities. A mix of commands, HelpEntries and FileHelpEntries.

  • search_fields (list) – A list of dicts defining how Lunr will find the search data on the elements. If not given, will use a default.

Returns:

tuple – A tuple (match, suggestions).

parse()[source]

input is a string containing the command or topic to match.

The allowed syntax is

help <topic>[/<subtopic>[/<subtopic>[/...]]]

The database/command query is always for <topic>, and any subtopics is then parsed from there. If a <topic> has spaces in it, it is always matched before assuming the space begins a subtopic.

strip_cmd_prefix(key, all_keys)[source]

Conditional strip of a command prefix, such as @ in @desc. By default this will be hidden unless there is a duplicate without the prefix in the full command set (such as @open and open).

Parameters:
  • key (str) – Command key to analyze.

  • all_cmds (list) – All command-keys (and potentially aliases).

Returns:

str – Potentially modified key to use in help display.

func()[source]

Run the dynamic help entry creator.

help_category = 'general'
lock_storage = 'cmd:all()'
search_index_entry = {'aliases': '?', 'category': 'general', 'key': 'help', 'no_prefix': ' ?', 'tags': '', 'text': "\nGet help.\n\nUsage:\n  help\n  help <topic, command or category>\n  help <topic>/<subtopic>\n  help <topic>/<subtopic>/<subsubtopic> ...\n\nUse the 'help' command alone to see an index of all help topics, organized\nby category. Some big topics may offer additional sub-topics.\n\n"}
class evennia.commands.default.help.CmdSetHelp(**kwargs)[source]

Bases: CmdHelp

Edit the help database.

Usage:
sethelp[/switches] <topic>[[;alias;alias][,category[,locks]]

[= <text or new value>]

Switches:

edit - open a line editor to edit the topic’s help text. replace - overwrite existing help topic. append - add text to the end of existing topic with a newline between. extend - as append, but don’t add a newline. category - change category of existing help topic. locks - change locks of existing help topic. delete - remove help topic.

Examples

sethelp lore = In the beginning was … sethelp/append pickpocketing,Thievery = This steals … sethelp/replace pickpocketing, ,attr(is_thief) = This steals … sethelp/edit thievery sethelp/locks thievery = read:all() sethelp/category thievery = classes

If not assigning a category, the settings.DEFAULT_HELP_CATEGORY category will be used. If no lockstring is specified, everyone will be able to read the help entry. Sub-topics are embedded in the help text.

Note that this cannot modify command-help entries - these are modified in-code, outside the game.

SUBTOPICS

Adding subtopics

Subtopics helps to break up a long help entry into sub-sections. Users can access subtopics with |whelp topic/subtopic/…|n Subtopics are created and stored together with the main topic.

To start adding subtopics, add the text ‘# SUBTOPICS’ on a new line at the end of your help text. After this you can now add any number of subtopics, each starting with ‘## <subtopic-name>’ on a line, followed by the help-text of that subtopic. Use ‘### <subsub-name>’ to add a sub-subtopic and so on. Max depth is 5. A subtopic’s title is case-insensitive and can consist of multiple words - the user will be able to enter a partial match to access it.

For example:

Main help text for <topic>

# SUBTOPICS

## about

Text for the ‘<topic>/about’ subtopic’

### more about-info

Text for the ‘<topic>/about/more about-info sub-subtopic

## extra

Text for the ‘<topic>/extra’ subtopic
key = 'sethelp'
aliases = []
switch_options = ('edit', 'replace', 'append', 'extend', 'category', 'locks', 'delete')
locks = 'cmd:perm(Helper)'
help_category = 'building'
arg_regex = None
parse()[source]

We want to use the default parser rather than the CmdHelp.parse

func()[source]

Implement the function

lock_storage = 'cmd:perm(Helper)'
search_index_entry = {'aliases': '', 'category': 'building', 'key': 'sethelp', 'no_prefix': ' ', 'tags': '', 'text': "\nEdit the help database.\n\nUsage:\n  sethelp[/switches] <topic>[[;alias;alias][,category[,locks]]\n            [= <text or new value>]\nSwitches:\n  edit - open a line editor to edit the topic's help text.\n  replace - overwrite existing help topic.\n  append - add text to the end of existing topic with a newline between.\n  extend - as append, but don't add a newline.\n  category - change category of existing help topic.\n  locks - change locks of existing help topic.\n  delete - remove help topic.\n\nExamples:\n  sethelp lore = In the beginning was ...\n  sethelp/append pickpocketing,Thievery = This steals ...\n  sethelp/replace pickpocketing, ,attr(is_thief) = This steals ...\n  sethelp/edit thievery\n  sethelp/locks thievery = read:all()\n  sethelp/category thievery = classes\n\nIf not assigning a category, the `settings.DEFAULT_HELP_CATEGORY` category\nwill be used. If no lockstring is specified, everyone will be able to read\nthe help entry.  Sub-topics are embedded in the help text.\n\nNote that this cannot modify command-help entries - these are modified\nin-code, outside the game.\n\n# SUBTOPICS\n\n## Adding subtopics\n\nSubtopics helps to break up a long help entry into sub-sections. Users can\naccess subtopics with |whelp topic/subtopic/...|n Subtopics are created and\nstored together with the main topic.\n\nTo start adding subtopics, add the text '# SUBTOPICS' on a new line at the\nend of your help text. After this you can now add any number of subtopics,\neach starting with '## <subtopic-name>' on a line, followed by the\nhelp-text of that subtopic.\nUse '### <subsub-name>' to add a sub-subtopic and so on. Max depth is 5. A\nsubtopic's title is case-insensitive and can consist of multiple words -\nthe user will be able to enter a partial match to access it.\n\nFor example:\n\n| Main help text for <topic>\n|\n| # SUBTOPICS\n|\n| ## about\n|\n| Text for the '<topic>/about' subtopic'\n|\n| ### more about-info\n|\n| Text for the '<topic>/about/more about-info sub-subtopic\n|\n| ## extra\n|\n| Text for the '<topic>/extra' subtopic\n\n"}
class evennia.commands.default.help.ANSIString(*args, **kwargs)[source]

Bases: str

Unicode-like object that is aware of ANSI codes.

This class can be used nearly identically to strings, in that it will report string length, handle slices, etc, much like a string object would. The methods should be used identically as string methods are.

There is at least one exception to this (and there may be more, though they have not come up yet). When using ‘’.join() or u’’.join() on an ANSIString, color information will get lost. You must use ANSIString(‘’).join() to preserve color information.

This implementation isn’t perfectly clean, as it doesn’t really have an understanding of what the codes mean in order to eliminate redundant characters– though cleaning up the strings might end up being inefficient and slow without some C code when dealing with larger values. Such enhancements could be made as an enhancement to ANSI_PARSER if needed, however.

If one is going to use ANSIString, one should generally avoid converting away from it until one is about to send information on the wire. This is because escape sequences in the string may otherwise already be decoded, and taken literally the second time around.

__init__(*_, **kwargs)[source]

When the ANSIString is first initialized, a few internal variables have to be set.

The first is the parser. It is possible to replace Evennia’s standard ANSI parser with one of your own syntax if you wish, so long as it implements the same interface.

The second is the _raw_string. This is the original “dumb” string with ansi escapes that ANSIString represents.

The third thing to set is the _clean_string. This is a string that is devoid of all ANSI Escapes.

Finally, _code_indexes and _char_indexes are defined. These are lookup tables for which characters in the raw string are related to ANSI escapes, and which are for the readable text.

capitalize(*args, **kwargs)

Return a capitalized version of the string.

More specifically, make the first character have upper case and the rest lower case.

center(width, fillchar, _difference)[source]

Center some text with some spaces padding both sides.

Parameters:
  • width (int) – The target width of the output string.

  • fillchar (str) – A single character string to pad the output string with.

Returns:

result (ANSIString) – A string padded on both ends with fillchar.

clean()[source]

Return a string object without the ANSI escapes.

Returns:

clean_string (str) – A unicode object with no ANSI escapes.

count(*args, **kwargs)

Return the number of non-overlapping occurrences of substring sub in string S[start:end].

Optional arguments start and end are interpreted as in slice notation.

decode(*args, **kwargs)
encode(*args, **kwargs)

Encode the string using the codec registered for encoding.

encoding

The encoding in which to encode the string.

errors

The error handling scheme to use for encoding errors. The default is ‘strict’ meaning that encoding errors raise a UnicodeEncodeError. Other possible values are ‘ignore’, ‘replace’ and ‘xmlcharrefreplace’ as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors.

endswith(*args, **kwargs)

Return True if the string ends with the specified suffix, False otherwise.

suffix

A string or a tuple of strings to try.

start

Optional start position. Default: start of the string.

end

Optional stop position. Default: end of the string.

expandtabs(*args, **kwargs)

Return a copy where all tab characters are expanded using spaces.

If tabsize is not given, a tab size of 8 characters is assumed.

find(*args, **kwargs)

Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end].

Optional arguments start and end are interpreted as in slice notation. Return -1 on failure.

format(*args, **kwargs)

Return a formatted version of the string, using substitutions from args and kwargs. The substitutions are identified by braces (‘{’ and ‘}’).

index(*args, **kwargs)

Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end].

Optional arguments start and end are interpreted as in slice notation. Raises ValueError when the substring is not found.

isalnum(*args, **kwargs)

Return True if the string is an alpha-numeric string, False otherwise.

A string is alpha-numeric if all characters in the string are alpha-numeric and there is at least one character in the string.

isalpha(*args, **kwargs)

Return True if the string is an alphabetic string, False otherwise.

A string is alphabetic if all characters in the string are alphabetic and there is at least one character in the string.

isdigit(*args, **kwargs)

Return True if the string is a digit string, False otherwise.

A string is a digit string if all characters in the string are digits and there is at least one character in the string.

islower(*args, **kwargs)

Return True if the string is a lowercase string, False otherwise.

A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.

isspace(*args, **kwargs)

Return True if the string is a whitespace string, False otherwise.

A string is whitespace if all characters in the string are whitespace and there is at least one character in the string.

istitle(*args, **kwargs)

Return True if the string is a title-cased string, False otherwise.

In a title-cased string, upper- and title-case characters may only follow uncased characters and lowercase characters only cased ones.

isupper(*args, **kwargs)

Return True if the string is an uppercase string, False otherwise.

A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.

join(iterable)[source]

Joins together strings in an iterable, using this string between each one.

NOTE: This should always be used for joining strings when ANSIStrings are involved. Otherwise color information will be discarded by python, due to details in the C implementation of strings.

Parameters:

iterable (list of strings) – A list of strings to join together

Returns:

ANSIString

A single string with all of the iterable’s

contents concatenated, with this string between each.

Examples

>>> ANSIString(', ').join(['up', 'right', 'left', 'down'])
ANSIString('up, right, left, down')
ljust(width, fillchar, _difference)[source]

Left justify some text.

Parameters:
  • width (int) – The target width of the output string.

  • fillchar (str) – A single character string to pad the output string with.

Returns:

result (ANSIString) – A string padded on the right with fillchar.

lower(*args, **kwargs)

Return a copy of the string converted to lowercase.

lstrip(chars=None)[source]

Strip from the left, taking ANSI markers into account.

Parameters:

chars (str, optional) – A string containing individual characters to strip off of the left end of the string. By default, any blank spaces are trimmed.

Returns:

result (ANSIString)

A new ANSIString with the left end trimmed of

the relevant characters.

partition(sep, reverse=False)[source]

Splits once into three sections (with the separator being the middle section)

We use the same techniques we used in split() to make sure each are colored.

Parameters:
  • sep (str) – The separator to split the string on.

  • reverse (boolean) – Whether to split the string on the last occurrence of the separator rather than the first.

Returns:

ANSIString – The part of the string before the separator ANSIString: The separator itself ANSIString: The part of the string after the separator.

raw()[source]

Return a string object with the ANSI escapes.

Returns:

raw (str) – A unicode object with the raw ANSI escape sequences.

re_format = re.compile('(?i)(?P<just>(?P<fill>.)?(?P<align>\\<|\\>|\\=|\\^))?(?P<sign>\\+|\\-| )?(?P<alt>\\#)?(?P<zero>0)?(?P<width>\\d+)?(?P<grouping>\\_|\\,)?(?:\\.(?P<precision>\\d+))?(?P<type>b|c|d|e|E|f|F|g|G|n|o|s|x|X, re.IGNORECASE)
replace(*args, **kwargs)

Return a copy with all occurrences of substring old replaced by new.

count

Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences.

If the optional argument count is given, only the first count occurrences are replaced.

rfind(*args, **kwargs)

Return the highest index in S where substring sub is found, such that sub is contained within S[start:end].

Optional arguments start and end are interpreted as in slice notation. Return -1 on failure.

rindex(*args, **kwargs)

Return the highest index in S where substring sub is found, such that sub is contained within S[start:end].

Optional arguments start and end are interpreted as in slice notation. Raises ValueError when the substring is not found.

rjust(width, fillchar, _difference)[source]

Right justify some text.

Parameters:
  • width (int) – The target width of the output string.

  • fillchar (str) – A single character string to pad the output string with.

Returns:

result (ANSIString) – A string padded on the left with fillchar.

rsplit(by=None, maxsplit=-1)[source]

Like split, but starts from the end of the string rather than the beginning.

Stolen from PyPy’s pure Python string implementation, tweaked for ANSIString.

PyPy is distributed under the MIT licence. http://opensource.org/licenses/MIT

Parameters:
  • by (str) – A string to search for which will be used to split the string. For instance, ‘,’ for ‘Hello,world’ would result in [‘Hello’, ‘world’]

  • maxsplit (int) – The maximum number of times to split the string. For example, a maxsplit of 2 with a by of ‘,’ on the string ‘Hello,world,test,string’ would result in [‘Hello,world’, ‘test’, ‘string’]

Returns:

result (list of ANSIStrings)

A list of ANSIStrings derived from

this string.

rstrip(chars=None)[source]

Strip from the right, taking ANSI markers into account.

Parameters:

chars (str, optional) – A string containing individual characters to strip off of the right end of the string. By default, any blank spaces are trimmed.

Returns:

result (ANSIString)

A new ANSIString with the right end trimmed of

the relevant characters.

split(by=None, maxsplit=-1)[source]

Splits a string based on a separator.

Stolen from PyPy’s pure Python string implementation, tweaked for ANSIString.

PyPy is distributed under the MIT licence. http://opensource.org/licenses/MIT

Parameters:
  • by (str) – A string to search for which will be used to split the string. For instance, ‘,’ for ‘Hello,world’ would result in [‘Hello’, ‘world’]

  • maxsplit (int) – The maximum number of times to split the string. For example, a maxsplit of 2 with a by of ‘,’ on the string ‘Hello,world,test,string’ would result in [‘Hello’, ‘world’, ‘test,string’]

Returns:

result (list of ANSIStrings)

A list of ANSIStrings derived from

this string.

startswith(*args, **kwargs)

Return True if the string starts with the specified prefix, False otherwise.

prefix

A string or a tuple of strings to try.

start

Optional start position. Default: start of the string.

end

Optional stop position. Default: end of the string.

strip(chars=None)[source]

Strip from both ends, taking ANSI markers into account.

Parameters:

chars (str, optional) – A string containing individual characters to strip off of both ends of the string. By default, any blank spaces are trimmed.

Returns:

result (ANSIString)

A new ANSIString with the ends trimmed of the

relevant characters.

swapcase(*args, **kwargs)

Convert uppercase characters to lowercase and lowercase characters to uppercase.

translate(*args, **kwargs)

Replace each character in the string using the given translation table.

table

Translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, strings, or None.

The table must implement lookup/indexing via __getitem__, for instance a dictionary or list. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted.

upper(*args, **kwargs)

Return a copy of the string converted to uppercase.

evennia.commands.default.help.COMMAND_DEFAULT_CLASS

alias of MuxCommand

class evennia.commands.default.help.EvEditor(caller, loadfunc=None, savefunc=None, quitfunc=None, key='', persistent=False, codefunc=False)[source]

Bases: object

This defines a line editor object. It creates all relevant commands and tracks the current state of the buffer. It also cleans up after itself.

__init__(caller, loadfunc=None, savefunc=None, quitfunc=None, key='', persistent=False, codefunc=False)[source]

Launches a full in-game line editor, mimicking the functionality of VIM.

Parameters:
  • caller (Object) – Who is using the editor.

  • loadfunc (callable, optional) – This will be called as loadfunc(caller) when the editor is first started. Its return will be used as the editor’s starting buffer.

  • savefunc (callable, optional) – This will be called as savefunc(caller, buffer) when the save-command is given and is used to actually determine where/how result is saved. It should return True if save was successful and also handle any feedback to the user.

  • quitfunc (callable, optional) – This will optionally be called as quitfunc(caller) when the editor is exited. If defined, it should handle all wanted feedback to the user.

  • quitfunc_args (tuple, optional) – Optional tuple of arguments to supply to quitfunc.

  • key (str, optional) – An optional key for naming this session and make it unique from other editing sessions.

  • persistent (bool, optional) – Make the editor survive a reboot. Note that if this is set, all callables must be possible to pickle

  • codefunc (bool, optional) – If given, will run the editor in code mode. This will be called as codefunc(caller, buf).

Notes

In persistent mode, all the input callables (savefunc etc) must be possible to be pickled, this excludes e.g. callables that are class methods or functions defined dynamically or as part of another function. In non-persistent mode no such restrictions exist.

decrease_indent()[source]

Decrease automatic indentation by 1 level.

deduce_indent(line, buffer)[source]

Try to deduce the level of indentation of the given line.

display_buffer(buf=None, offset=0, linenums=True, options={'raw': False})[source]

This displays the line editor buffer, or selected parts of it.

Parameters:
  • buf (str, optional) – The buffer or part of buffer to display.

  • offset (int, optional) – If buf is set and is not the full buffer, offset should define the actual starting line number, to get the linenum display right.

  • linenums (bool, optional) – Show line numbers in buffer.

  • options – raw (bool, optional): Tell protocol to not parse formatting information.

display_help()[source]

Shows the help entry for the editor.

get_buffer()[source]
Returns:

buffer (str) – The current buffer.

increase_indent()[source]

Increase automatic indentation by 1 level.

load_buffer()[source]

Load the buffer using the load function hook.

quit()[source]

Cleanly exit the editor.

save_buffer()[source]

Saves the content of the buffer.

swap_autoindent()[source]

Swap automatic indentation on or off.

update_buffer(buf)[source]

This should be called when the buffer has been changed somehow. It will handle unsaved flag and undo updating.

Parameters:

buf (str) – The text to update the buffer with.

update_undo(step=None)[source]

This updates the undo position.

Parameters:

step (int, optional) – The amount of steps to progress the undo position to. This may be a negative value for undo and a positive value for redo.

class evennia.commands.default.help.HelpCategory(key: str)[source]

Bases: object

Mock ‘help entry’ to search categories with the same code.

key: str
property search_index_entry
__init__(key: str) None
class evennia.commands.default.help.HelpEntry(*args, **kwargs)[source]

Bases: SharedMemoryModel

A generic help entry.

An HelpEntry object has the following properties defined:

key - main name of entry help_category - which category entry belongs to (defaults to General) entrytext - the actual help text permissions - perm strings

Method:

access

exception DoesNotExist

Bases: ObjectDoesNotExist

exception MultipleObjectsReturned

Bases: MultipleObjectsReturned

access(accessing_obj, access_type='read', default=True)[source]

Determines if another object has permission to access this help entry.

Accesses used by default:

‘read’ - read the help entry itself. ‘view’ - see help entry in help index.

Parameters:
  • accessing_obj (Object or Account) – Entity trying to access this one.

  • access_type (str) – type of access sought.

  • default (bool) – What to return if no lock of access_type was found.

aliases[source]
property date_created

Return the field in localized time based on settings.TIME_ZONE.

db_date_created

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

db_entrytext

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

db_help_category

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

db_key

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

db_lock_storage

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

db_tags

Accessor to the related objects manager on the forward and reverse sides of a many-to-many relation.

In the example:

class Pizza(Model):
    toppings = ManyToManyField(Topping, related_name='pizzas')

**Pizza.toppings** and **Topping.pizzas** are **ManyToManyDescriptor** instances.

Most of the implementation is delegated to a dynamically defined manager class built by **create_forward_many_to_many_manager()** defined below.

property entrytext

A wrapper for getting database field db_entrytext.

get_absolute_url()

Returns the URI path for a View that allows users to view details for this object.

ex. Oscar (Character) = ‘/characters/oscar/1/’

For this to work, the developer must have defined a named view somewhere in urls.py that follows the format ‘modelname-action’, so in this case a named view of ‘character-detail’ would be referenced by this method.

ex.

url(r'characters/(?P<slug>[\w\d\-]+)/(?P<pk>[0-9]+)/$',
    CharDetailView.as_view(), name='character-detail')

If no View has been created and defined in urls.py, returns an HTML anchor.

This method is naive and simply returns a path. Securing access to the actual view and limiting who can view this object is the developer’s responsibility.

Returns:

path (str) – URI path to object detail page, if defined.

get_next_by_db_date_created(*, field=<django.db.models.fields.DateTimeField: db_date_created>, is_next=True, **kwargs)
get_previous_by_db_date_created(*, field=<django.db.models.fields.DateTimeField: db_date_created>, is_next=False, **kwargs)
property help_category

A wrapper for getting database field db_help_category.

id

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

property key

A wrapper for getting database field db_key.

property lock_storage

A wrapper for getting database field db_lock_storage.

locks[source]
objects = <evennia.help.manager.HelpEntryManager object>
path = 'evennia.help.models.HelpEntry'
property search_index_entry

Property for easily retaining a search index entry for this object.

tags[source]
typename = 'SharedMemoryModelBase'
web_get_admin_url()[source]

Returns the URI path for the Django Admin page for this object.

ex. Account#1 = ‘/admin/accounts/accountdb/1/change/’

Returns:

path (str) – URI path to Django Admin page for object.

classmethod web_get_create_url()[source]

Returns the URI path for a View that allows users to create new instances of this object.

ex. Chargen = ‘/characters/create/’

For this to work, the developer must have defined a named view somewhere in urls.py that follows the format ‘modelname-action’, so in this case a named view of ‘character-create’ would be referenced by this method.

ex.

url(r'characters/create/', ChargenView.as_view(), name='character-create')

If no View has been created and defined in urls.py, returns an HTML anchor.

This method is naive and simply returns a path. Securing access to the actual view and limiting who can create new objects is the developer’s responsibility.

Returns:

path (str) – URI path to object creation page, if defined.

web_get_delete_url()[source]

Returns the URI path for a View that allows users to delete this object.

ex. Oscar (Character) = ‘/characters/oscar/1/delete/’

For this to work, the developer must have defined a named view somewhere in urls.py that follows the format ‘modelname-action’, so in this case a named view of ‘character-detail’ would be referenced by this method.

ex.

url(r'characters/(?P<slug>[\w\d\-]+)/(?P<pk>[0-9]+)/delete/$',
    CharDeleteView.as_view(), name='character-delete')

If no View has been created and defined in urls.py, returns an HTML anchor.

This method is naive and simply returns a path. Securing access to the actual view and limiting who can delete this object is the developer’s responsibility.

Returns:

path (str) – URI path to object deletion page, if defined.

web_get_detail_url()[source]

Returns the URI path for a View that allows users to view details for this object.

ex. Oscar (Character) = ‘/characters/oscar/1/’

For this to work, the developer must have defined a named view somewhere in urls.py that follows the format ‘modelname-action’, so in this case a named view of ‘character-detail’ would be referenced by this method.

ex.

url(r'characters/(?P<slug>[\w\d\-]+)/(?P<pk>[0-9]+)/$',
    CharDetailView.as_view(), name='character-detail')

If no View has been created and defined in urls.py, returns an HTML anchor.

This method is naive and simply returns a path. Securing access to the actual view and limiting who can view this object is the developer’s responsibility.

Returns:

path (str) – URI path to object detail page, if defined.

web_get_update_url()[source]

Returns the URI path for a View that allows users to update this object.

ex. Oscar (Character) = ‘/characters/oscar/1/change/’

For this to work, the developer must have defined a named view somewhere in urls.py that follows the format ‘modelname-action’, so in this case a named view of ‘character-update’ would be referenced by this method.

ex.

url(r'characters/(?P<slug>[\w\d\-]+)/(?P<pk>[0-9]+)/change/$',
    CharUpdateView.as_view(), name='character-update')

If no View has been created and defined in urls.py, returns an HTML anchor.

This method is naive and simply returns a path. Securing access to the actual view and limiting who can modify objects is the developer’s responsibility.

Returns:

path (str) – URI path to object update page, if defined.

exception evennia.commands.default.help.LockException[source]

Bases: Exception

Raised during an error in a lock.

class evennia.commands.default.help.chain(*iterables)

Bases: object

Return a chain object whose .__next__() method returns elements from the first iterable until it is exhausted, then elements from the next iterable, until all of the iterables are exhausted.

classmethod from_iterable(iterable, /)

Alternative chain() constructor taking a single iterable argument that evaluates lazily.

evennia.commands.default.help.class_from_module(path, defaultpaths=None, fallback=None)[source]

Return a class from a module, given the class’ full python path. This is primarily used to convert db_typeclass_path:s to classes.

Parameters:
  • path (str) – Full Python dot-path to module.

  • defaultpaths (iterable, optional) – If a direct import from path fails, try subsequent imports by prepending those paths to path.

  • fallback (str) – If all other attempts fail, use this path as a fallback. This is intended as a last-resort. In the example of Evennia loading, this would be a path to a default parent class in the evennia repo itself.

Returns:

class (Class) – An uninstantiated class recovered from path.

Raises:

ImportError – If all loading failed.

evennia.commands.default.help.dataclass(cls=None, /, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False)[source]

Add dunder methods based on the fields defined in the class.

Examines PEP 526 __annotations__ to determine fields.

If init is true, an __init__() method is added to the class. If repr is true, a __repr__() method is added. If order is true, rich comparison dunder methods are added. If unsafe_hash is true, a __hash__() method is added. If frozen is true, fields may not be assigned to after instance creation. If match_args is true, the __match_args__ tuple is added. If kw_only is true, then by default all fields are keyword-only. If slots is true, a new class with a __slots__ attribute is returned.

evennia.commands.default.help.dedent(text, baseline_index=None, indent=None)[source]

Safely clean all whitespace at the left of a paragraph.

Parameters:
  • text (str) – The text to dedent.

  • baseline_index (int, optional) – Which row to use as a ‘base’ for the indentation. Lines will be dedented to this level but no further. If None, indent so as to completely deindent the least indented text.

  • indent (int, optional) – If given, force all lines to this indent. This bypasses baseline_index.

Returns:

text (str) – Dedented string.

Notes

This is useful for preserving triple-quoted string indentation while still shifting it all to be next to the left edge of the display.

class evennia.commands.default.help.defaultdict

Bases: dict

defaultdict(default_factory=None, /, […]) –> dict with default factory

The default factory is called without arguments to produce a new value when a key is not present, in __getitem__ only. A defaultdict compares equal to a dict with the same items. All remaining arguments are treated the same as if they were passed to the dict constructor, including keyword arguments.

__init__(*args, **kwargs)
copy() a shallow copy of D.
default_factory

Factory for default value called by __missing__().

evennia.commands.default.help.format_grid(elements, width=78, sep='  ', verbatim_elements=None, line_prefix='')[source]

This helper function makes a ‘grid’ output, where it distributes the given string-elements as evenly as possible to fill out the given width. will not work well if the variation of length is very big!

Parameters:
  • elements (iterable) – A 1D list of string elements to put in the grid.

  • width (int, optional) – The width of the grid area to fill.

  • sep (str, optional) – The extra separator to put between words. If set to the empty string, words may run into each other.

  • verbatim_elements (list, optional) – This is a list of indices pointing to specific items in the elements list. An element at this index will not be included in the calculation of the slot sizes. It will still be inserted into the grid at the correct position and may be surrounded by padding unless filling the entire line. This is useful for embedding decorations in the grid, such as horizontal bars.

  • ignore_ansi (bool, optional) – Ignore ansi markups when calculating white spacing.

  • line_prefix (str, optional) – A prefix to add at the beginning of each line. This can e.g. be used to preserve line color across line breaks.

Returns:

list – The grid as a list of ready-formatted rows. We return it like this to make it easier to insert decorations between rows, such as horizontal bars.

evennia.commands.default.help.help_search_with_index(query, candidate_entries, suggestion_maxnum=5, fields=None)[source]

Lunr-powered fast index search and suggestion wrapper. See https://lunrjs.com/.

Parameters:
  • query (str) – The query to search for.

  • candidate_entries (list) – This is the body of possible entities to search. Each must have a property .search_index_entry that returns a dict with all keys in the fields arg.

  • suggestion_maxnum (int) – How many matches to allow at most in a multi-match.

  • fields (list, optional) – A list of Lunr field mappings **{“field_name”: str, “boost”: int}**. See the Lunr documentation for more details. The field name must exist in the dicts returned by .search_index_entry of the candidates. If not given, a default setup is used, prefering keys > aliases > category > tags.

Returns:

tuple

A tuple (matches, suggestions), each a list, where the suggestion_maxnum limits

how many suggestions are included.

evennia.commands.default.help.inherits_from(obj, parent)[source]

Takes an object and tries to determine if it inherits at any distance from parent.

Parameters:
  • obj (any) – Object to analyze. This may be either an instance or a class.

  • parent (any) – Can be either an instance, a class or the python path to the class.

Returns:

inherits_from (bool) – If parent is a parent to obj or not.

Notes

What differentiates this function from Python’s isinstance() is the flexibility in the types allowed for the object and parent being compared.

evennia.commands.default.help.pad(text, width=None, align='c', fillchar=' ')[source]

Pads to a given width.

Parameters:
  • text (str) – Text to pad.

  • width (int, optional) – The width to pad to, in characters.

  • align (str, optional) – This is one of ‘c’, ‘l’ or ‘r’ (center, left or right).

  • fillchar (str, optional) – The character to fill with.

Returns:

text (str) – The padded text.

evennia.commands.default.help.parse_entry_for_subcategories(entry)[source]

Parse a command docstring for special sub-category blocks:

Parameters:

entry (str) – A help entry to parse

Returns:

dict

The dict is a mapping that splits the entry into subcategories. This

will always hold a key None for the main help entry and zero or more keys holding the subcategories. Each is itself a dict with a key None for the main text of that subcategory followed by any sub-sub-categories down to a max-depth of 5.

Example:

'''
Main topic text

# SUBTOPICS

## foo

A subcategory of the main entry, accessible as **help topic foo**
(or using /, like **help topic/foo**)

## bar

Another subcategory, accessed as **help topic bar**
(or **help topic/bar**)

### moo

A subcategory of bar, accessed as **help bar moo**
(or **help bar/moo**)

#### dum

A subcategory of moo, accessed **help bar moo dum**
(or **help bar/moo/dum**)

'''

This will result in this returned entry structure:

{
   None: "Main topic text":
   "foo": {
        None: "main topic/foo text"
   },
   "bar": {
        None: "Main topic/bar text",
        "moo": {
            None: "topic/bar/moo text"
            "dum": {
                None: "topic/bar/moo/dum text"
            }
        }
   }
}