Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

API Documentation Bugs #2290

Closed
8 of 15 tasks
Thom1729 opened this issue May 6, 2018 · 28 comments
Closed
8 of 15 tasks

API Documentation Bugs #2290

Thom1729 opened this issue May 6, 2018 · 28 comments

Comments

@Thom1729
Copy link

Thom1729 commented May 6, 2018

I've gone through the API documentation and compared it to the sublime package source to come up a list of inconsistencies. Most of these fall neatly into one of two categories:

Undocumented functions or methods

A good many functions and methods are not documented. In some cases, this may be deliberate. In these cases, the function or method might benefit from a comment indicating that the feature is for internal use only. In other cases, the functionality might be very useful to package developers and ought to be documented. The following examples stand out:

Incorrect argument names

In many instances, the documented argument names do not match the names in the Python source. This matters when developers try to call API functions and methods using keyword arguents. Because some API methods have many optional arguments, this can be a real obstacle for developers. What inspired me to compile this list was the Window.show_quick_panel method. The signature described in the documentation is:

show_quick_panel(items, on_done, <flags>, <selected_index>, <on_highlighted>)

However, the actual signature is:

show_quick_panel(items, on_select, <flags>, <selected_index>, <on_highlight>)

There are two possible remedies to this: to change the documentation or to change the module. Changing the documentation is easier and does not run the risk of breaking code. In some cases, the argument names in the documentation may help to document the type of the argument; this information might instead be documented in the style of Python 3.5 type hints:

run_command(
    cmd: string,
    args: dict
)

It would be possible to alter the argument names without breaking compatibility by using a decorator mapping old argument names to the current documented names (and possibly emitting a deprecation warning). This might be a good way to preserve backward compatibility in a new version of sublime for a new Python runtime.

sublime

Undocumented functions

  • channel()
  • executable_path()
  • executable_hash()
  • status_message(msg)
  • log_indexing(msg)
  • log_build_systems(msg)

Incorrect argument names

Function Actual Name Documented Name Notes
error_message msg string
ok_cancel_dialog msg string
ok_cancel_dialog ok_title An empty string will be ignored.
yes_no_cancel_dialog msg string
yes_no_cancel_dialog yes_title An empty string will be ignored.
yes_no_cancel_dialog no_title An empty string will be ignored.
run_command cmd string
set_clipboard_command text string
score_selector scope_name scope
encode_value val value
decode_value data string
expand_variables val value
set_timeout f callback
set_timeout timeout_ms delay Optional, defaults to 0.
set_timeout_async f callback
set_timeout_async timeout_ms delay Optional, defaults to 0.

Window

Undocumented methods

  • Window(self, id) (probably private)
  • hwnd(self) (probably private)
  • transient_sheet_in_group(self, group)
  • transient_view_in_group(self, group)
  • layout(self)
  • get_layout(self) (deprecated)
  • set_layout(self, layout)
  • get_output_panel(self, name) (deprecated)
  • settings(self)
  • template_settings(self)
  • lookup_references_in_index(self, sym)
  • lookup_references_in_open_files(self, sym)

Incorrect argument names

Method Actual Name Documented Name Notes
run_command cmd string
open_file fname file_name
open_file flag The FORCE_GROUP flag is undocumented.
open_file group undocumented
find_open_file fname file_name
focus_group idx group
set_sheet_index idx index
set_view_index idx index
show_quick_panel on_select on_done
show_quick_panel on_highlight on_highlighted
set_project_data v data
lookup_symbol_in_index sym symbol
lookup_symbol_in_open_files sym symbol
status_message msg string
new_file flags undocumented
new_file syntax undocumented

Region

Undocumented methods

  • __str__(self)
  • __repr__(self)
  • __len__(self)
  • __eq__(self, rhs)
  • __lt__(self, rhs)

Incorrect argument names

Method Actual Name Documented Name Notes
Region b Optional, defaults to a.
Region xpos undocumented
contains x region and point
cover rhs region
intersection rhs region
intersects rhs region

Notes

The implementation of __lt__ is a bit idiosyncratic. Because the method is undocumented, it might be safe to redefine the operator in a new version of the API.

Selection

Undocumented methods

  • Selection(self, id) (probably private)
  • __len__(self)
  • __getitem__(self, index)
  • __delitem__(self, index)
  • __eq__(self, rhs)
  • __lt__(self, rhs)
  • __bool__(self)
  • is_valid(self)

Incorrect argument names

Method Actual Name Documented Name Notes
add x region

Notes

The __iter__ method is not implemented. Iteration over a Selection will still work because Python will fall back to using __len__ and __getitem__, but some modern means of checking for iterability may fail on Selection instances.

View

Undocumented methods

  • View(self, id) (probably private)
  • __len__(self)
  • __eq__(self, other)
  • __bool__(self)
  • is_valid(self)
  • close(self)
  • retarget(self, new_fname)
  • begin_edit(self, edit_token, cmd, args) (probably private)
  • end_edit(self, edit) (probably private)
  • is_in_edit(self) (probably private)
  • meta_info(self, key, pt)
  • indented_region(self, pt)
  • indentation_level(self, pt)
  • has_non_empty_selection_region(self)
  • is_folded(self, sr)
  • folded_regions(self)
  • add_phantom(self, key)
  • erase_phantoms(self, key)
  • erase_phantom_by_id(self, pid)
  • query_phantom(self, pid)
  • query_phantoms(self, pids)
  • assign_syntax(self, syntax_file)
  • indexed_symbols(self)
  • indexed_references(self)
  • extract_completions(self, prefix, tp)
  • find_all_results(self)
  • find_all_results_with_text(self)

Incorrect argument names

Method Actual Name Documented Name Notes
set_read_only read_only value
set_scratch scratch value
set_encoding encoding_name encoding
set_line_endings line_ending_name line_endings
insert pt point
insert text string
erase r region
replace r region
replace text string
run_command cmd string
substr x region or point
find start_pt start_point
find_all fmt format
extract_scope pt point
scope_name pt point
match_selector pt point
score_selector pt point
style_for_scope scope scope_name
line x region or point
full_line x region or point
word x region or point
classify pt point
find_by_class pt point
expand_by_class x region or point
rowcol tp point
show x location
show show_surrounds What does this do?
show_at_center x location
set_viewport_position xy
set_viewport_position animate typo: <animate<
text_to_layout tp point
text_to_window tp point
layout_to_text xy vector
layout_to_window xy vector
window_to_layout xy vector
window_to_text xy vector
fold x region or [regions]
unfold x region or [regions]
command_history delta index
set_overwrite_status value enabled
show_popup_menu on_select on_done

Phantom

Undocumented methods

  • __eq__(self, rhs)

PhantomSet

Undocumented methods

  • __del__(self)

Incorrect argument names

Method Actual Name Documented Name Notes
__init__ key Optional, defaults to "".
update new_phantoms phantoms
@jrappen
Copy link
Contributor

jrappen commented May 6, 2018

Also related: #2146

@OdatNurd
Copy link

OdatNurd commented Jun 8, 2018

In a similar vein, see #1883 w/regards to the documented return value of the description method of all of the command classes potentially being wrong.

@titoBouzout
Copy link
Collaborator

@wbond it would be nice to have some (at least) of this undocumented stuff on the official documentation, took me a while to understand why view.run_command('close') wasnt working and to notice there's an undocumented method view.close()

OdatNurd added a commit to STealthy-and-haSTy/SnAPI that referenced this issue Nov 1, 2018
Per the list in sublimehq/sublime_text#2290
this makes some changes to the parameter names of some API functions to
better match what the real underlying parameter in the methods are
called.

The main impetus for this change is to change some of the optional
arguments to API functions that you sometimes use keyword arguments for
which are misnamed in the documentation.

Along with that, some parameter names have also been renamed where my
(probably faultly) judgment deems the replacement with the underlying
actual name makes the document a bit more readable.

In a similar vein, not all such items in the issue above have been
modified because in many cases the actual name makes the documentation
less readable (again in my probably faulty judgement), not more readable
as one would hope.

An example of such is the `fold` and `unfold` API functions, which take
actual arguments named `x` but which the document calls `region` or
`[regions]`, which is much more readable for the purposes of knowing
what it does.
@Cerberus-tm
Copy link

Cerberus-tm commented Nov 15, 2019

Very interesting! Now I wonder how wise it would be to use those undocumented functions/methods in a plug-in: might they be retracted or changed in future versions of Sublime? Some look very nice, though...

@FichteFoll
Copy link
Collaborator

Many of these are in use by plugins and I suspect its unlikely for them to be removed without notice, maybe excluding those that already have been deprecated.

The next big release of ST specifically aims to keep compatibility where possible.

@jrappen
Copy link
Contributor

jrappen commented Nov 27, 2019

Also related: #2905

@jrappen
Copy link
Contributor

jrappen commented Nov 27, 2019

Also related: #2691

@jrappen
Copy link
Contributor

jrappen commented Nov 27, 2019

also related #2721

@jrappen
Copy link
Contributor

jrappen commented Nov 28, 2019

This old blog post has some more:

https://thume.ca/2016/12/03/disassembling-sublime-text/

@jrappen
Copy link
Contributor

jrappen commented Dec 12, 2019

⚠️ A typo in the list above where rowcall should've been rowcol.

@jfcherng
Copy link

jfcherng commented Apr 28, 2020

#1488 may worth to be written in the docs about with_prototype if it's not going to be fixed.


UPDATE: this has been fixed in 4075

@rchl
Copy link

rchl commented Sep 15, 2020

Key Bindings documentation (http://www.sublimetext.com/docs/key_bindings.html#keys) should mention the <character> key also (catches all alphanumeric characters, I believe).

@rchl
Copy link

rchl commented Sep 20, 2020

  • the sublime.CompletionItem accepts flags argument but it's not documented [1]
  • the CompletionItem.snippet_completion and CompletionItem.command_completion class methods should also accept the same flags argument (this is both a documentation and core issue) and set it on the sublime.CompletionItem instance that they create.
  • I believe the only flag that is supported currently is sublime.COMPLETION_FLAG_KEEP_PREFIX, also not documented

(Not being able to pass flags to the class methods means that one currently has to create an instance of sublime.CompletionItem and then update the flags property manually on the created instance.)

[1] http://www.sublimetext.com/docs/api_reference.html#sublime.CompletionItem:ver-dev

@jrappen
Copy link
Contributor

jrappen commented Oct 9, 2020

(as a docs issue) related to: #3684

@rchl
Copy link

rchl commented Oct 16, 2020

Not API related but I've spent too much time figuring out a particular syntax handling behavior that confused me.

So with:

push:
  - include: context-1
  - include: context-2
  - include: context-3

, if context-2 pushes another context on the stack and then pops back, shown contexts will be evaluated from the top again (starting from context-1) rather than continuing to context-3.

I think it would be worth clarifying that in the syntax documentation.

@FichteFoll
Copy link
Collaborator

I've checked a few functions that have since been added (with the release of 4095), but there are still many missing, whether by mistake or by choice.

@wbond
Copy link
Member

wbond commented Jan 23, 2021

By choice. There is a lot to do, and I wanted to make sure I got everything new documented. I also got some older stuff documented, but decided there were some other higher priority items I needed to tackle.

@jrappen
Copy link
Contributor

jrappen commented May 27, 2022

Docs have seen some major updates today.

https://www.sublimetext.com/docs/index.html


Haven't checked against the list above.

@FichteFoll
Copy link
Collaborator

FichteFoll commented Jun 7, 2022

There are a few obvious errors in the type annotations of sublime.py which is used to build the documentation now. I've made a few quick amendmends that reflect the actual behavior, but some annotations are still wrong or incomplete. Generally, the Value, Point, DIP, and CommandArgs types should be defined either as an alias or as a new type that is then explained in text (as it is currently). Some internal type aliases could proved to be useful regardless of whether they are documented as such.
Additionally, some __eq__ implementations don't check for the object's class where the initial rhs argument should be an object. A simple mypy run on the file should yield most of the remaining problems.

--- /opt/sublime_text/Lib/python38/sublime.py	Fri May 27 11:32:43 2022
+++ /opt/sublime_text/Lib/python38/sublime.py	Tue Jun  7 12:43:14 2022
@@ -10,7 +10,7 @@
 import sys
 import io
 import enum
-from typing import Callable, Optional, Any, Iterator, Union, Dict, List, Tuple
+from typing import Callable, Optional, Any, Iterator, Union, Dict, List, Tuple, Literal
 
 import sublime_api
 
@@ -777,7 +777,7 @@
 
 def open_dialog(
         callback: Callable[[Union[str, List[str], None]], None],
-        file_types: [(str, [str])] = [],
+        file_types: List[Tuple[str, List[str]]] = [],
         directory: Optional[str] = None,
         multi_select=False,
         allow_folders=False):
@@ -812,7 +812,7 @@
 
 def save_dialog(
         callback: Callable[[Union[str, None]], None],
-        file_types: [(str, [str])] = [],
+        file_types: List[Tuple[str, List[str]]] = [],
         directory: Optional[str] = None,
         name: Optional[str] = None,
         extension: Optional[str] = None):
@@ -1119,7 +1119,7 @@
     return bytes
 
 
-def find_resources(pattern: str) -> [str]:
+def find_resources(pattern: str) -> List[str]:
     """
     Finds resources whose file name matches the given glob pattern.
     """
@@ -1204,14 +1204,14 @@
     return Window(sublime_api.active_window())
 
 
-def windows() -> [Window]:
+def windows() -> List[Window]:
     """
     :returns: A list of all the open windows.
     """
     return [Window(id) for id in sublime_api.windows()]
 
 
-def get_macro() -> [dict]:
+def get_macro() -> List[Dict[str, Value]]:
     """
     :returns: A list of the commands and args that compromise the currently
               recorded macro. Each ``dict`` will contain the keys ``"command"``
@@ -1226,8 +1226,8 @@
 
     def __init__(self, id: int):
         self.window_id = id
-        self.settings_object = None
-        self.template_settings_object = None
+        self.settings_object: Optional[Settings] = None
+        self.template_settings_object: Optional[Settings] = None
 
     def __hash__(self) -> int:
         return self.window_id
@@ -1338,7 +1338,7 @@
         else:
             return View(view_id)
 
-    def file_history(self) -> [str]:
+    def file_history(self) -> List[str]:
         """
         Get the list of previously opened files. This is the same list
         as *File > Open Recent*.
@@ -1377,7 +1377,7 @@
         if view:
             sublime_api.window_focus_view(self.window_id, view.view_id)
 
-    def select_sheets(self, sheets: [Sheet]):
+    def select_sheets(self, sheets: List[Sheet]):
         """
         Change the selected sheets for the entire window.
 
@@ -1391,7 +1391,7 @@
         """
         sublime_api.window_bring_to_front(self.window_id)
 
-    def get_sheet_index(self, sheet: Sheet) -> (int, int):
+    def get_sheet_index(self, sheet: Sheet) -> Tuple[int, int]:
         """
         :returns: The a tuple of the group and index within the group of the
                   given `Sheet`.
@@ -1401,7 +1401,7 @@
         else:
             return (-1, -1)
 
-    def get_view_index(self, view: View) -> (int, int):
+    def get_view_index(self, view: View) -> Tuple[int, int]:
         """
         :returns: The a tuple of the group and index within the group of the
                   given `View`.
@@ -1423,7 +1423,7 @@
         """
         sublime_api.window_set_view_index(self.window_id, view.view_id, group, index)
 
-    def move_sheets_to_group(self, sheets: [Sheet], group: int, insertion_idx = -1, select = True):
+    def move_sheets_to_group(self, sheets: List[Sheet], group: int, insertion_idx = -1, select = True):
         """
         Moves all provided sheets to specified group at insertion index
         provided. If an index is not provided defaults to last index of the
@@ -1444,14 +1444,14 @@
             sheet_ids.append(sheet.id())
         sublime_api.window_move_sheets_to_group(self.window_id, sheet_ids, group, insertion_idx, select)
 
-    def sheets(self) -> [Sheet]:
+    def sheets(self) -> List[Sheet]:
         """
         :returns: All open sheets in the window.
         """
         sheet_ids = sublime_api.window_sheets(self.window_id)
         return [make_sheet(x) for x in sheet_ids]
 
-    def views(self, *, include_transient=False) -> [View]:
+    def views(self, *, include_transient=False) -> List[View]:
         """
         :param include_transient: Whether the transient sheet should be included.
 
@@ -1461,7 +1461,7 @@
         view_ids = sublime_api.window_views(self.window_id, include_transient)
         return [View(x) for x in view_ids]
 
-    def selected_sheets(self) -> [Sheet]:
+    def selected_sheets(self) -> List[Sheet]:
         """
         .. since:: 4083
 
@@ -1470,7 +1470,7 @@
         sheet_ids = sublime_api.window_selected_sheets(self.window_id)
         return [make_sheet(s) for s in sheet_ids]
 
-    def selected_sheets_in_group(self, group: int) -> [Sheet]:
+    def selected_sheets_in_group(self, group: int) -> List[Sheet]:
         """
         .. since:: 4083
 
@@ -1499,21 +1499,21 @@
         else:
             return View(view_id)
 
-    def sheets_in_group(self, group: int) -> [Sheet]:
+    def sheets_in_group(self, group: int) -> List[Sheet]:
         """
         :returns: A list of all sheets in the specified group.
         """
         sheet_ids = sublime_api.window_sheets_in_group(self.window_id, group)
         return [make_sheet(x) for x in sheet_ids]
 
-    def views_in_group(self, group: int) -> [View]:
+    def views_in_group(self, group: int) -> List[View]:
         """
         :returns: A list of all views in the specified group.
         """
         view_ids = sublime_api.window_views_in_group(self.window_id, group)
         return [View(x) for x in view_ids]
 
-    def transient_sheet_in_group(self, group: int) -> Sheet:
+    def transient_sheet_in_group(self, group: int) -> Optional[Sheet]:
         """
         :returns: The transient sheet in the specified group.
         """
@@ -1523,7 +1523,7 @@
         else:
             return None
 
-    def transient_view_in_group(self, group: int) -> View:
+    def transient_view_in_group(self, group: int) -> Optional[View]:
         """
         :returns: The transient view in the specified group.
         """
@@ -1533,7 +1533,7 @@
         else:
             return None
 
-    def layout(self) -> Dict[str, sublime.Value]:
+    def layout(self) -> Dict[str, Value]:
         """
         Get the group layout of the window.
         """
@@ -1545,7 +1545,7 @@
         """
         return sublime_api.window_get_layout(self.window_id)
 
-    def set_layout(self, layout: Dict[str, sublime.Value]):
+    def set_layout(self, layout: Dict[str, Value]):
         """
         Set the group layout of the window.
         """
@@ -1563,7 +1563,7 @@
         """
         return View(sublime_api.window_create_output_panel(self.window_id, name, unlisted))
 
-    def find_output_panel(self, name: str) -> View:
+    def find_output_panel(self, name: str) -> Optional[View]:
         """
         :returns:
             The `View` associated with the named output panel, or ``None`` if
@@ -1587,7 +1587,7 @@
         name = sublime_api.window_active_panel(self.window_id)
         return name or None
 
-    def panels(self) -> [str]:
+    def panels(self) -> List[str]:
         """
         Returns a list of the names of all panels that have not been marked as
         unlisted. Includes certain built-in panels in addition to output
@@ -1810,28 +1810,28 @@
 
         return sublime_api.window_symbol_locations(self.window_id, sym, source, type, kind_id, letter)
 
-    def lookup_symbol_in_index(self, symbol: str) -> [SymbolLocation]:
+    def lookup_symbol_in_index(self, symbol: str) -> List[SymbolLocation]:
         """
         :returns: All locations where the symbol is defined across files in the current project.
         :deprecated: Use `symbol_locations()` instead.
         """
         return sublime_api.window_lookup_symbol(self.window_id, symbol)
 
-    def lookup_symbol_in_open_files(self, symbol: str) -> [SymbolLocation]:
+    def lookup_symbol_in_open_files(self, symbol: str) -> List[SymbolLocation]:
         """
         :returns: All locations where the symbol is defined across open files.
         :deprecated: Use `symbol_locations()` instead.
         """
         return sublime_api.window_lookup_symbol_in_open_files(self.window_id, symbol)
 
-    def lookup_references_in_index(self, symbol: str) -> [SymbolLocation]:
+    def lookup_references_in_index(self, symbol: str) -> List[SymbolLocation]:
         """
         :returns: All locations where the symbol is referenced across files in the current project.
         :deprecated: Use `symbol_locations()` instead.
         """
         return sublime_api.window_lookup_references(self.window_id, symbol)
 
-    def lookup_references_in_open_files(self, symbol: str) -> [SymbolLocation]:
+    def lookup_references_in_open_files(self, symbol: str) -> List[SymbolLocation]:
         """
         :returns: All locations where the symbol is referenced across open files.
         :deprecated: Use `symbol_locations()` instead.
@@ -1932,7 +1932,7 @@
         """ :returns: The size of the region. """
         return self.size()
 
-    def __eq__(self, rhs: Region) -> bool:
+    def __eq__(self, rhs: object) -> bool:
         """
         :returns: Whether the two regions are identical. Ignores ``xpos``.
         """
@@ -1971,7 +1971,7 @@
                 "in <Region> requires int or Region as left operand"
                 f", not {fq_name}")
 
-    def to_tuple(self) -> (Point, Point):
+    def to_tuple(self) -> Tuple[Point, Point]:
         """
         .. since:: 4075
 
@@ -2228,7 +2228,7 @@
     def __hash__(self) -> int:
         return self.sheet_id
 
-    def __eq__(self, other: Sheet) -> bool:
+    def __eq__(self, other: object) -> bool:
         return isinstance(other, Sheet) and other.sheet_id == self.sheet_id
 
     def __repr__(self) -> str:
@@ -2402,7 +2402,7 @@
     def __hash__(self) -> int:
         return self.view_id
 
-    def __eq__(self, other: View) -> bool:
+    def __eq__(self, other: object) -> bool:
         return isinstance(other, View) and other.view_id == self.view_id
 
     def __bool__(self) -> bool:
@@ -2489,7 +2489,7 @@
         """
         return sublime_api.view_is_primary(self.view_id)
 
-    def window(self) -> Optional[None]:
+    def window(self) -> Optional[Window]:
         """
         :returns: A reference to the window containing the view, if any.
         """
@@ -2499,7 +2499,7 @@
         else:
             return Window(window_id)
 
-    def clones(self) -> [View]:
+    def clones(self) -> List[View]:
         """ :returns: All the other views into the same `Buffer`. See `View`. """
         return list(map(View, sublime_api.view_clones(self.view_id)))
 
@@ -2658,7 +2658,7 @@
         """
         return sublime_api.view_change_count(self.view_id)
 
-    def change_id(self) -> (int, int, int):
+    def change_id(self) -> Tuple[int, int, int]:
         """
         Get a 3-element tuple that can be passed to `transform_region_from()` to
         obtain a region equivalent to a region of the view in the past. This is
@@ -2668,7 +2668,7 @@
         """
         return sublime_api.view_change_id(self.view_id)
 
-    def transform_region_from(self, region: Region, change_id: (int, int, int)) -> Region:
+    def transform_region_from(self, region: Region, change_id: Tuple[int, int, int]) -> Region:
         """
         Transforms a region from a previous point in time to an equivalent
         region in the current state of the View. The ``change_id`` must have
@@ -2708,7 +2708,7 @@
         """
         return sublime_api.view_find(self.view_id, pattern, start_pt, flags)
 
-    def find_all(self, pattern: str, flags=FindFlags.NONE, fmt: Optional[str] = None, extractions: Optional[List[str]] = None) -> [Region]:
+    def find_all(self, pattern: str, flags=FindFlags.NONE, fmt: Optional[str] = None, extractions: Optional[List[str]] = None) -> List[Region]:
         """
         :param pattern: The regex or literal pattern to search by.
         :param flags: Controls various behaviors of find. See `FindFlags`.
@@ -2747,7 +2747,7 @@
         """
         return sublime_api.view_meta_info(self.view_id, key, pt)
 
-    def extract_tokens_with_scopes(self, region: Region) -> List[(Region, str)]:
+    def extract_tokens_with_scopes(self, region: Region) -> List[Tuple[Region, str]]:
         """
         :param region: The region from which to extract tokens and scopes.
         :returns: A list of pairs containing the `Region` and the scope of each token.
@@ -2865,7 +2865,7 @@
         """
         return sublime_api.view_lines(self.view_id, region)
 
-    def split_by_newlines(self, region: Region) -> [Region]:
+    def split_by_newlines(self, region: Region) -> List[Region]:
         """
         Splits the region up such that each `Region` returned exists on exactly
         one line.
@@ -2939,14 +2939,14 @@
         else:
             return sublime_api.view_expand_by_class(self.view_id, x, x, classes, separators, sub_word_separators)
 
-    def rowcol(self, tp: Point) -> (int, int):
+    def rowcol(self, tp: Point) -> Tuple[int, int]:
         """
         Calculates the 0-based line and column numbers of the point. Column
         numbers are returned as number of Unicode characters.
         """
         return sublime_api.view_row_col(self.view_id, tp)
 
-    def rowcol_utf8(self, tp: Point) -> (int, int):
+    def rowcol_utf8(self, tp: Point) -> Tuple[int, int]:
         """
         Calculates the 0-based line and column numbers of the point. Column
         numbers are returned as UTF-8 code units.
@@ -2955,7 +2955,7 @@
         """
         return sublime_api.view_row_col_utf8(self.view_id, tp)
 
-    def rowcol_utf16(self, tp: Point) -> (int, int):
+    def rowcol_utf16(self, tp: Point) -> Tuple[int, int]:
         """
         Calculates the 0-based line and column numbers of the point. Column
         numbers are returned as UTF-16 code units.
@@ -3118,8 +3118,8 @@
         else:
             return sublime_api.view_unfold_regions(self.view_id, x)
 
-    def add_regions(self, key: str, regions: [Region], scope="",
-                    icon="", flags=RegionFlags.NONE, annotations: [str] = [],
+    def add_regions(self, key: str, regions: List[Region], scope="",
+                    icon="", flags=RegionFlags.NONE, annotations: List[str] = [],
                     annotation_color="",
                     on_navigate: Optional[Callable[[str], None]] = None,
                     on_close: Optional[Callable[[], None]] = None):
@@ -3192,7 +3192,7 @@
         sublime_api.view_add_regions(
             self.view_id, key, regions, scope, icon, flags, annotations, annotation_color, on_navigate, on_close)
 
-    def get_regions(self, key: str) -> [Region]:
+    def get_regions(self, key: str) -> List[Region]:
         """
         :returns: The regions associated with the given ``key``, if any.
         """
@@ -3214,10 +3214,10 @@
     def erase_phantom_by_id(self, pid: int):
         sublime_api.view_erase_phantom(self.view_id, pid)
 
-    def query_phantom(self, pid: int) -> [Region]:
+    def query_phantom(self, pid: int) -> List[Region]:
         return sublime_api.view_query_phantoms(self.view_id, [pid])
 
-    def query_phantoms(self, pids: [int]) -> [Region]:
+    def query_phantoms(self, pids: List[int]) -> List[Region]:
         return sublime_api.view_query_phantoms(self.view_id, pids)
 
     def assign_syntax(self, syntax: Union[str, Syntax]):
@@ -3322,13 +3322,13 @@
         """
         return sublime_api.view_extract_completions(self.view_id, prefix, tp)
 
-    def find_all_results(self) -> [(str, int, int)]:
+    def find_all_results(self) -> List[Tuple[str, int, int]]:
         return sublime_api.view_find_all_results(self.view_id)
 
-    def find_all_results_with_text(self) -> [(str, int, int, str)]:
+    def find_all_results_with_text(self) -> List[Tuple[str, int, int, str]]:
         return sublime_api.view_find_all_results_with_text(self.view_id)
 
-    def command_history(self, index: int, modifying_only=False) -> (str, CommandArgs, int):
+    def command_history(self, index: int, modifying_only=False) -> Tuple[str, CommandArgs, int]:
         """
         Get info on previous run commands stored in the undo/redo stack.
 
@@ -3355,7 +3355,7 @@
         """ Set the overwrite status. See `overwrite_status()`. """
         sublime_api.view_set_overwrite_status(self.view_id, value)
 
-    def show_popup_menu(self, items: [str], on_done: Callable[[int], None], flags=0):
+    def show_popup_menu(self, items: List[str], on_done: Callable[[int], None], flags=0):
         """
         Show a popup menu at the caret, for selecting an item in a list.
 
@@ -3490,7 +3490,7 @@
     def __hash__(self) -> int:
         return self.buffer_id
 
-    def __eq__(self, other: Buffer) -> bool:
+    def __eq__(self, other: object) -> bool:
         return isinstance(other, Buffer) and self.buffer_id == other.buffer_id
 
     def __repr__(self) -> str:
@@ -3517,7 +3517,7 @@
         else:
             return name
 
-    def views(self) -> [View]:
+    def views(self) -> List[View]:
         """
         Returns a list of all views that are associated with this buffer.
         """
@@ -3695,7 +3695,7 @@
         return (f'Phantom({self.region!r}, {self.content!r}, '
                 f'{self.layout!r}, on_navigate={self.on_navigate!r})')
 
-    def to_tuple(self) -> ((Point, Point), str, PhantomLayout, Optional[Callable[[str], None]]):
+    def to_tuple(self) -> Tuple[Tuple[Point, Point], str, PhantomLayout, Optional[Callable[[str], None]]]:
         """
         Returns a tuple of this phantom containing the region, content, layout
         and callback.
@@ -3941,7 +3941,7 @@
             details)
 
 
-def list_syntaxes() -> [Syntax]:
+def list_syntaxes() -> List[Syntax]:
     """ List all known syntaxes.
 
     Returns a list of Syntax.
@@ -3957,7 +3957,7 @@
     return sublime_api.get_syntax(path)
 
 
-def find_syntax_by_name(name: str) -> [Syntax]:
+def find_syntax_by_name(name: str) -> List[Syntax]:
     """ Find syntaxes with the specified name.
 
     Name must match exactly. Return a list of Syntax.
@@ -3965,7 +3965,7 @@
     return [syntax for syntax in list_syntaxes() if syntax.name == name]
 
 
-def find_syntax_by_scope(scope: str) -> [Syntax]:
+def find_syntax_by_scope(scope: str) -> List[Syntax]:
     """ Find syntaxes with the specified scope.
 
     Scope must match exactly. Return a list of Syntax.
@@ -4009,7 +4009,7 @@
         self.scope: str = scope
         """ The base scope name of the syntax. """
 
-    def __eq__(self, other: Syntax) -> bool:
+    def __eq__(self, other: object) -> bool:
         return isinstance(other, Syntax) and self.path == other.path
 
     def __hash__(self) -> int:

@deathaxe
Copy link
Collaborator

deathaxe commented Jun 7, 2022

  1. I'm uncertain whether sublime.CommandArgs = Optional[Dict[str, Value]] is a good idea, given that command_history returns Tuple[str, CommandArgs, int], which CommandArgs are a mandatory item of.

  2. With type alias something like

    DIP = int
    Point = int
    Value = str
    CommandArgs = Dict[str, Value]
    Vector = Tuple[DIP, DIP]
    
    Kind = Tuple[KindId, str, str]
    """
    Metadata about the kind of a symbol, `CompletionItem`, `QuickPanelItem` or `ListInputItem`.
    Controls the color and letter shown in the “icon” presented to the left of the item.
    
    .. since:: 4052
    """

    is meant?

@FichteFoll
Copy link
Collaborator

Yes, those are type aliases (basically storing the type in a variable for re-use). However, I suspect that type aliases are resolved during the documentation build process, meaning their naming (and their semantic meaning) would be lost. A TypeVar with a lower bound could be created as a workaround for these, though I also don't know how those would end up in the generated documentation.

@rchl
Copy link

rchl commented Jun 8, 2022

In the new documentation, all of the classes within the sublime module are partially transparent indicating that those were introduced after the 4 version (in dev version) which I don't think is true. At least not for all of them.

Screenshot 2022-06-08 at 09 06 48

@jfcherng
Copy link

jfcherng commented Jun 8, 2022

LGTM. I mean all of those classes are introduced as of 4132 indeed. But this page doesn't mention how those constants can be used in pre-4132.

# as of 4132
class HoverZone(enum.IntEnum):
    TEXT = 1
    GUTTER = 2
    MARGIN = 3
HOVER_TEXT = HoverZone.TEXT
HOVER_GUTTER = HoverZone.GUTTER
HOVER_MARGIN = HoverZone.MARGIN

# pre-4132
HOVER_TEXT = 1
HOVER_GUTTER = 2
HOVER_MARGIN = 3

In pre-4132, you can only use HOVER_TEXT, HOVER_GUTTER and HOVER_MARGIN. There is no HoverZone in pre-4132.

@rchl
Copy link

rchl commented Jun 8, 2022

Oh, didn't realize that those are wrappers/aliases for existing functionality. Ignore me.

@jwortmann
Copy link

But HOVER_TEXT, HOVER_GUTTER and HOVER_MARGIN are not mentioned in the docs now.

They are mentioned:

For backwards compatibility these values are also available outside this enumeration with a HOVER_ prefix.

@BenjaminSchaaf
Copy link
Member

For reference the reason I didn't put the type aliases within the sublime module and instead kept them inside the documentation is that sphinx simply does not understand type aliases.

@deathaxe

I'm uncertain whether sublime.CommandArgs = Optional[Dict[str, Value]] is a good idea, given that command_history returns Tuple[str, CommandArgs, int], which CommandArgs are a mandatory item of.

command_history returns ('', None, 0) when the index is out of range.

@deathaxe
Copy link
Collaborator

Unfortunately type checkers like mypy or pyright complain about absence of DIP, Value, etc. definitions.

Well, I learned Optional[x] == Union[X,None]. Just have been under the impression it means the argument can be omitted.

@BenjaminSchaaf
Copy link
Member

The new documentation fixes the vast majority of issues here. Type annotation issues are covered by this issue: #3283, so I'm going to close this issue. If there are more specific issues with the documentation please post a separate issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests