Show possible abbreviations in help list
[mudpy.git] / mudpy / command.py
1 """User command functions for the mudpy engine."""
2
3 # Copyright (c) 2004-2019 mudpy authors. Permission to use, copy,
4 # modify, and distribute this software is granted under terms
5 # provided in the LICENSE file distributed with this software.
6
7 import random
8 import re
9 import unicodedata
10
11 import mudpy
12
13
14 def chat(actor, parameters):
15     """Toggle chat mode."""
16     mode = actor.get("mode")
17     if not mode:
18         actor.set("mode", "chat")
19         actor.send("Entering chat mode (use $(grn)!chat$(nrm) to exit).")
20     elif mode == "chat":
21         actor.remove_facet("mode")
22         actor.send("Exiting chat mode.")
23     else:
24         actor.send("Sorry, but you're already busy with something else!")
25
26
27 def create(actor, parameters):
28     """Create an element if it does not exist."""
29     if not parameters:
30         message = "You must at least specify an element to create."
31     elif not actor.owner:
32         message = ""
33     else:
34         arguments = parameters.split()
35         if len(arguments) == 1:
36             arguments.append("")
37         if len(arguments) == 2:
38             element, filename = arguments
39             if element in actor.universe.contents:
40                 message = 'The "' + element + '" element already exists.'
41             else:
42                 message = ('You create "' +
43                            element + '" within the universe.')
44                 logline = actor.owner.account.get(
45                     "name"
46                 ) + " created an element: " + element
47                 if filename:
48                     logline += " in file " + filename
49                     if filename not in actor.universe.files:
50                         message += (
51                             ' Warning: "' + filename + '" is not yet '
52                             "included in any other file and will not be read "
53                             "on startup unless this is remedied.")
54                 mudpy.misc.Element(element, actor.universe, filename)
55                 mudpy.misc.log(logline, 6)
56         elif len(arguments) > 2:
57             message = "You can only specify an element and a filename."
58     actor.send(message)
59
60
61 def delete(actor, parameters):
62     """Delete a facet from an element."""
63     if not parameters:
64         message = "You must specify an element and a facet."
65     else:
66         arguments = parameters.split(" ")
67         if len(arguments) == 1:
68             message = ('What facet of element "' + arguments[0]
69                        + '" would you like to delete?')
70         elif len(arguments) != 2:
71             message = "You may only specify an element and a facet."
72         else:
73             element, facet = arguments
74             if element not in actor.universe.contents:
75                 message = 'The "' + element + '" element does not exist.'
76             elif facet not in actor.universe.contents[element].facets():
77                 message = ('The "' + element + '" element has no "' + facet
78                            + '" facet.')
79             else:
80                 actor.universe.contents[element].remove_facet(facet)
81                 message = ('You have successfully deleted the "' + facet
82                            + '" facet of element "' + element
83                            + '". Try "show element ' +
84                            element + '" for verification.')
85     actor.send(message)
86
87
88 def destroy(actor, parameters):
89     """Destroy an element if it exists."""
90     if actor.owner:
91         if not parameters:
92             message = "You must specify an element to destroy."
93         else:
94             if parameters not in actor.universe.contents:
95                 message = 'The "' + parameters + '" element does not exist.'
96             else:
97                 actor.universe.contents[parameters].destroy()
98                 message = ('You destroy "' + parameters
99                            + '" within the universe.')
100                 mudpy.misc.log(
101                     actor.owner.account.get(
102                         "name"
103                     ) + " destroyed an element: " + parameters,
104                     6
105                 )
106         actor.send(message)
107
108
109 def error(actor, input_data):
110     """Generic error for an unrecognized command word."""
111
112     # 90% of the time use a generic error
113     if random.randrange(10):
114         message = '''I'm not sure what "''' + input_data + '''" means...'''
115
116     # 10% of the time use the classic diku error
117     else:
118         message = "Arglebargle, glop-glyf!?!"
119
120     # send the error message
121     actor.send(message)
122
123
124 def halt(actor, parameters):
125     """Halt the world."""
126     if actor.owner:
127
128         # see if there's a message or use a generic one
129         if parameters:
130             message = "Halting: " + parameters
131         else:
132             message = "User " + actor.owner.account.get(
133                 "name"
134             ) + " halted the world."
135
136         # let everyone know
137         mudpy.misc.broadcast(message, add_prompt=False)
138         mudpy.misc.log(message, 8)
139
140         # set a flag to terminate the world
141         actor.universe.terminate_flag = True
142
143
144 def help(actor, parameters):
145     """List available commands and provide help for commands."""
146
147     # did the user ask for help on a specific command word?
148     if parameters and actor.owner:
149
150         # is the command word one for which we have data?
151         command = mudpy.misc.find_command(parameters)
152
153         # only for allowed commands
154         if actor.can_run(command):
155
156             # add a description if provided
157             description = command.get("description")
158             if not description:
159                 description = "(no short description provided)"
160             if command.get("administrative"):
161                 output = "$(red)"
162             else:
163                 output = "$(grn)"
164             output = "%s%s$(nrm) - %s$(eol)$(eol)" % (
165                 output, command.subkey, description)
166
167             # add the help text if provided
168             help_text = command.get("help")
169             if not help_text:
170                 help_text = "No help is provided for this command."
171             output += help_text
172
173             # list related commands
174             see_also = command.get("see_also")
175             if see_also:
176                 really_see_also = ""
177                 for item in see_also:
178                     if item in actor.universe.groups["command"]:
179                         command = actor.universe.groups["command"][item]
180                         if actor.can_run(command):
181                             if really_see_also:
182                                 really_see_also += ", "
183                             if command.get("administrative"):
184                                 really_see_also += "$(red)"
185                             else:
186                                 really_see_also += "$(grn)"
187                             really_see_also += item + "$(nrm)"
188                 if really_see_also:
189                     output += "$(eol)$(eol)See also: " + really_see_also
190
191         # no data for the requested command word
192         else:
193             output = "That is not an available command."
194
195     # no specific command word was indicated
196     else:
197
198         # preamble text
199         output = ("These are the commands available to you [brackets indicate "
200                   "optional portion]:$(eol)$(eol)")
201
202         # list command names in alphabetical order
203         for command_name, command in sorted(
204                 actor.universe.groups["command"].items()):
205
206             # skip over disallowed commands
207             if actor.can_run(command):
208
209                 # start incrementing substrings
210                 for position in range(1, len(command_name) + 1):
211
212                     # we've found our shortest possible abbreviation
213                     candidate = mudpy.misc.find_command(
214                             command_name[:position])
215                     try:
216                         if candidate.subkey == command_name:
217                             break
218                     except AttributeError:
219                         pass
220
221                 # use square brackets to indicate optional part of command name
222                 if position < len(command_name):
223                     abbrev = "%s[%s]" % (
224                         command_name[:position], command_name[position:])
225                 else:
226                     abbrev = command_name
227
228                 # supply a useful default if the short description is missing
229                 description = command.get(
230                     "description", "(no short description provided)")
231
232                 # administrative command names are in red, others in green
233                 if command.get("administrative"):
234                     color = "red"
235                 else:
236                     color = "grn"
237
238                 # format the entry for this command
239                 output = "%s   $(%s)%s$(nrm) - %s$(eol)" % (
240                     output, color, abbrev, description)
241
242         # add a footer with instructions on getting additional information
243         output = ('%s $(eol)Enter "help COMMAND" for help on a command named '
244                   '"COMMAND".' % output)
245
246     # send the accumulated output to the user
247     actor.send(output)
248
249
250 def look(actor, parameters):
251     """Look around."""
252     if parameters:
253         actor.send("You can't look at or in anything yet.")
254     else:
255         actor.look_at(actor.get("location"))
256
257
258 def move(actor, parameters):
259     """Move the avatar in a given direction."""
260     if parameters in actor.universe.contents[actor.get("location")].portals():
261         actor.move_direction(parameters)
262     else:
263         actor.send("You cannot go that way.")
264
265
266 def preferences(actor, parameters):
267     """List, view and change actor preferences."""
268
269     # Escape replacement macros in preferences
270     parameters = mudpy.misc.escape_macros(parameters)
271
272     message = ""
273     arguments = parameters.split()
274     allowed_prefs = set()
275     user_config = actor.universe.contents.get("mudpy.user")
276     if user_config:
277         allowed_prefs.update(user_config.get("pref_allow", []))
278         if actor.owner.account.get("administrator"):
279             allowed_prefs.update(user_config.get("pref_admin", []))
280     if not arguments:
281         message += "These are your current preferences:"
282         for pref in allowed_prefs:
283             message += ("$(eol)   $(red)%s $(grn)%s$(nrm)"
284                         % (pref, actor.owner.account.get(pref)))
285     elif arguments[0] not in allowed_prefs:
286         message += (
287             'Preference "%s" does not exist. Try the `preferences` command by '
288             "itself for a list of valid preferences." % arguments[0])
289     elif len(arguments) == 1:
290         message += "%s" % actor.owner.account.get(arguments[0])
291     else:
292         pref = arguments[0]
293         value = " ".join(arguments[1:])
294         try:
295             actor.owner.account.set(pref, value)
296             message += 'Preference "%s" set to "%s".' % (pref, value)
297         except ValueError:
298             message = (
299                 'Preference "%s" cannot be set to type "%s".' % (
300                     pref, type(value)))
301     actor.send(message)
302
303
304 def quit(actor, parameters):
305     """Leave the world and go back to the main menu."""
306     if actor.owner:
307         actor.owner.state = "main_utility"
308         actor.owner.deactivate_avatar()
309
310
311 def reload(actor, parameters):
312     """Reload all code modules, configs and data."""
313     if actor.owner:
314
315         # let the user know and log
316         actor.send("Reloading all code modules, configs and data.")
317         mudpy.misc.log(
318             "User " +
319             actor.owner.account.get("name") + " reloaded the world.",
320             6
321         )
322
323         # set a flag to reload
324         actor.universe.reload_flag = True
325
326
327 def say(actor, parameters):
328     """Speak to others in the same area."""
329
330     # check for replacement macros and escape them
331     parameters = mudpy.misc.escape_macros(parameters)
332
333     # if the message is wrapped in quotes, remove them and leave contents
334     # intact
335     if parameters.startswith('"') and parameters.endswith('"'):
336         message = parameters[1:-1]
337         literal = True
338
339     # otherwise, get rid of stray quote marks on the ends of the message
340     else:
341         message = parameters.strip('''"'`''')
342         literal = False
343
344     # the user entered a message
345     if message:
346
347         # match the punctuation used, if any, to an action
348         if "mudpy.linguistic" in actor.universe.contents:
349             actions = actor.universe.contents[
350                 "mudpy.linguistic"].get("actions", {})
351             default_punctuation = (actor.universe.contents[
352                 "mudpy.linguistic"].get("default_punctuation", "."))
353         else:
354             actions = {}
355             default_punctuation = "."
356         action = ""
357
358         # reverse sort punctuation options so the longest match wins
359         for mark in sorted(actions.keys(), reverse=True):
360             if not literal and message.endswith(mark):
361                 action = actions[mark]
362                 break
363
364         # add punctuation if needed
365         if not action:
366             action = actions[default_punctuation]
367             if message and not (
368                literal or unicodedata.category(message[-1]) == "Po"
369                ):
370                 message += default_punctuation
371
372         # failsafe checks to avoid unwanted reformatting and null strings
373         if message and not literal:
374
375             # decapitalize the first letter to improve matching
376             message = message[0].lower() + message[1:]
377
378             # iterate over all words in message, replacing typos
379             if "mudpy.linguistic" in actor.universe.contents:
380                 typos = actor.universe.contents[
381                     "mudpy.linguistic"].get("typos", {})
382             else:
383                 typos = {}
384             words = message.split()
385             for index in range(len(words)):
386                 word = words[index]
387                 while unicodedata.category(word[0]) == "Po":
388                     word = word[1:]
389                 while unicodedata.category(word[-1]) == "Po":
390                     word = word[:-1]
391                 if word in typos.keys():
392                     words[index] = words[index].replace(word, typos[word])
393             message = " ".join(words)
394
395             # capitalize the first letter
396             message = message[0].upper() + message[1:]
397
398     # tell the area
399     if message:
400         actor.echo_to_location(
401             actor.get("name") + " " + action + 's, "' + message + '"'
402         )
403         actor.send("You " + action + ', "' + message + '"')
404
405     # there was no message
406     else:
407         actor.send("What do you want to say?")
408
409
410 def c_set(actor, parameters):
411     """Set a facet of an element."""
412     if not parameters:
413         message = "You must specify an element, a facet and a value."
414     else:
415         arguments = parameters.split(" ", 2)
416         if len(arguments) == 1:
417             message = ('What facet of element "' + arguments[0]
418                        + '" would you like to set?')
419         elif len(arguments) == 2:
420             message = ('What value would you like to set for the "' +
421                        arguments[1] + '" facet of the "' + arguments[0]
422                        + '" element?')
423         else:
424             element, facet, value = arguments
425             if element not in actor.universe.contents:
426                 message = 'The "' + element + '" element does not exist.'
427             else:
428                 try:
429                     actor.universe.contents[element].set(facet, value)
430                 except PermissionError:
431                     message = ('The "%s" element is kept in read-only file '
432                                '"%s" and cannot be altered.' %
433                                (element, actor.universe.contents[
434                                         element].origin.source))
435                 except ValueError:
436                     message = ('Value "%s" of type "%s" cannot be coerced '
437                                'to the correct datatype for facet "%s".' %
438                                (value, type(value), facet))
439                 else:
440                     message = ('You have successfully (re)set the "' + facet
441                                + '" facet of element "' + element
442                                + '". Try "show element ' +
443                                element + '" for verification.')
444     actor.send(message)
445
446
447 def show(actor, parameters):
448     """Show program data."""
449     message = ""
450     arguments = parameters.split()
451     if not parameters:
452         message = "What do you want to show?"
453     elif arguments[0] == "version":
454         message = repr(actor.universe.versions)
455     elif arguments[0] == "time":
456         message = "%s increments elapsed since the world was created." % (
457             str(actor.universe.groups["internal"]["counters"].get("elapsed")))
458     elif arguments[0] == "groups":
459         message = "These are the element groups:$(eol)"
460         groups = list(actor.universe.groups.keys())
461         groups.sort()
462         for group in groups:
463             message += "$(eol)   $(grn)" + group + "$(nrm)"
464     elif arguments[0] == "files":
465         message = "These are the current files containing the universe:$(eol)"
466         filenames = sorted(actor.universe.files)
467         for filename in filenames:
468             if actor.universe.files[filename].is_writeable():
469                 status = "rw"
470             else:
471                 status = "ro"
472             message += ("$(eol)   $(red)(%s) $(grn)%s$(nrm)" %
473                         (status, filename))
474             if actor.universe.files[filename].flags:
475                 message += (" $(yel)[%s]$(nrm)" %
476                             ",".join(actor.universe.files[filename].flags))
477     elif arguments[0] == "group":
478         if len(arguments) != 2:
479             message = "You must specify one group."
480         elif arguments[1] in actor.universe.groups:
481             message = ('These are the elements in the "' + arguments[1]
482                        + '" group:$(eol)')
483             elements = [
484                 (
485                     actor.universe.groups[arguments[1]][x].key
486                 ) for x in actor.universe.groups[arguments[1]].keys()
487             ]
488             elements.sort()
489             for element in elements:
490                 message += "$(eol)   $(grn)" + element + "$(nrm)"
491         else:
492             message = 'Group "' + arguments[1] + '" does not exist.'
493     elif arguments[0] == "file":
494         if len(arguments) != 2:
495             message = "You must specify one file."
496         elif arguments[1] in actor.universe.files:
497             message = ('These are the nodes in the "' + arguments[1]
498                        + '" file:$(eol)')
499             elements = sorted(actor.universe.files[arguments[1]].data)
500             for element in elements:
501                 message += "$(eol)   $(grn)" + element + "$(nrm)"
502         else:
503             message = 'File "%s" does not exist.' % arguments[1]
504     elif arguments[0] == "element":
505         if len(arguments) != 2:
506             message = "You must specify one element."
507         elif arguments[1].strip(".") in actor.universe.contents:
508             element = actor.universe.contents[arguments[1].strip(".")]
509             message = ('These are the properties of the "' + arguments[1]
510                        + '" element (in "' + element.origin.source
511                        + '"):$(eol)')
512             facets = element.facets()
513             for facet in sorted(facets):
514                 message += ("$(eol)   $(grn)%s: $(red)%s$(nrm)" %
515                             (facet, str(facets[facet])))
516         else:
517             message = 'Element "' + arguments[1] + '" does not exist.'
518     elif arguments[0] == "result":
519         if len(arguments) < 2:
520             message = "You need to specify an expression."
521         else:
522             try:
523                 message = repr(eval(" ".join(arguments[1:])))
524             except Exception as e:
525                 message = ("$(red)Your expression raised an exception...$(eol)"
526                            "$(eol)$(bld)%s$(nrm)" % e)
527     elif arguments[0] == "log":
528         if len(arguments) == 4:
529             if re.match(r"^\d+$", arguments[3]) and int(arguments[3]) >= 0:
530                 stop = int(arguments[3])
531             else:
532                 stop = -1
533         else:
534             stop = 0
535         if len(arguments) >= 3:
536             if re.match(r"^\d+$", arguments[2]) and int(arguments[2]) > 0:
537                 start = int(arguments[2])
538             else:
539                 start = -1
540         else:
541             start = 10
542         if len(arguments) >= 2:
543             if (re.match(r"^\d+$", arguments[1])
544                     and 0 <= int(arguments[1]) <= 9):
545                 level = int(arguments[1])
546             else:
547                 level = -1
548         elif 0 <= actor.owner.account.get("loglevel", 0) <= 9:
549             level = actor.owner.account.get("loglevel", 0)
550         else:
551             level = 1
552         if level > -1 and start > -1 and stop > -1:
553             message = mudpy.misc.get_loglines(level, start, stop)
554         else:
555             message = ("When specified, level must be 0-9 (default 1), "
556                        "start and stop must be >=1 (default 10 and 1).")
557     else:
558         message = '''I don't know what "''' + parameters + '" is.'
559     actor.send(message)