Skip to content

Commit

Permalink
Use settings.get() in more places (#1351)
Browse files Browse the repository at this point in the history
Builds on #1349 by converting most uses of `setting = mod.setting()` in
community to `settings.get()`.

@lunixbochs, would appreciate a quick look to make sure this is
correctly using settings.

---------

Co-authored-by: Nicholas Riley <com-github@sabi.net>
  • Loading branch information
brief and nriley authored Jan 15, 2024
1 parent 6e561c1 commit d904b4b
Show file tree
Hide file tree
Showing 18 changed files with 180 additions and 151 deletions.
6 changes: 3 additions & 3 deletions apps/emacs/emacs.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import logging
from typing import Optional

from talon import Context, Module, actions
from talon import Context, Module, actions, settings

mod = Module()
setting_meta = mod.setting(
mod.setting(
"emacs_meta",
type=str,
default="esc",
Expand All @@ -28,7 +28,7 @@


def meta(keys):
m = setting_meta.get()
m = settings.get("user.emacs_meta")
if m == "alt":
return " ".join("alt-" + k for k in keys.split())
elif m == "cmd":
Expand Down
6 changes: 3 additions & 3 deletions apps/mintty/mintty_win.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import subprocess

from talon import Context, Module, actions, ui
from talon import Context, Module, actions, settings, ui

mod = Module()
mod.apps.mintty = """
Expand All @@ -26,7 +26,7 @@
directories_to_remap = {}
directories_to_exclude = {}

setting_cyg_path = mod.setting(
mod.setting(
"cygpath",
type=str,
default="C:\\cygwin64\\bin\\cygpath.exe",
Expand All @@ -41,7 +41,7 @@ def get_win_path(cyg_path):
si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
path = (
subprocess.check_output(
[setting_cyg_path.get(), "-w", cyg_path], startupinfo=si
[settings.get("user.cygpath"), "-w", cyg_path], startupinfo=si
)
.strip(b"\n")
.decode()
Expand Down
6 changes: 3 additions & 3 deletions apps/tmux/tmux.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from talon import Context, Module, actions
from talon import Context, Module, actions, settings

mod = Module()

Expand All @@ -7,7 +7,7 @@
and tag: user.tmux
"""

setting_tmux_prefix_key = mod.setting(
mod.setting(
"tmux_prefix_key",
type=str,
default="ctrl-b",
Expand All @@ -19,7 +19,7 @@
class TmuxActions:
def tmux_prefix():
"""press control and the configured tmux prefix key"""
actions.key(f"{setting_tmux_prefix_key.get()}")
actions.key(settings.get("user.tmux_prefix_key"))

def tmux_keybind(key: str):
"""press tmux prefix followed by a key bind"""
Expand Down
6 changes: 3 additions & 3 deletions core/deprecations.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,12 @@ def legacy_capture(m) -> str:
import os.path
import warnings

from talon import Module, actions, speech_system
from talon import Module, actions, settings, speech_system

REPO_DIR = os.path.dirname(os.path.dirname(__file__))

mod = Module()
setting_deprecate_warning_interval_hours = mod.setting(
mod.setting(
"deprecate_warning_interval_hours",
type=float,
desc="""How long, in hours, to wait before notifying the user again of a
Expand Down Expand Up @@ -98,7 +98,7 @@ def deprecate_notify(id: str, message: str):

maybe_last_shown = notification_last_shown.get(id)
now = datetime.datetime.now()
interval = setting_deprecate_warning_interval_hours.get()
interval = settings.get("user.deprecate_warning_interval_hours")
threshold = now - datetime.timedelta(hours=interval)
if maybe_last_shown is not None and maybe_last_shown > threshold:
return
Expand Down
30 changes: 16 additions & 14 deletions core/help/help.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,18 @@
from itertools import islice
from typing import Iterable

from talon import Context, Module, actions, imgui, registry
from talon import Context, Module, actions, imgui, registry, settings

mod = Module()
mod.list("help_contexts", desc="list of available contexts")
mod.tag("help_open", "tag for commands that are available only when help is visible")
setting_help_max_contexts_per_page = mod.setting(
mod.setting(
"help_max_contexts_per_page",
type=int,
default=20,
desc="Max contexts to display per page in help",
)
setting_help_max_command_lines_per_page = mod.setting(
mod.setting(
"help_max_command_lines_per_page",
type=int,
default=50,
Expand Down Expand Up @@ -109,20 +109,22 @@ def format_context_button(index: int, context_label: str, context_name: str) ->

# translates 1-based index -> actual index in sorted_context_map_keys
def get_context_page(index: int) -> int:
return math.ceil(index / setting_help_max_contexts_per_page.get())
return math.ceil(index / settings.get("user.help_max_contexts_per_page"))


def get_total_context_pages() -> int:
return math.ceil(
len(sorted_display_list) / setting_help_max_contexts_per_page.get()
len(sorted_display_list) / settings.get("user.help_max_contexts_per_page")
)


def get_current_context_page_length() -> int:
start_index = (current_context_page - 1) * setting_help_max_contexts_per_page.get()
start_index = (current_context_page - 1) * settings.get(
"user.help_max_contexts_per_page"
)
return len(
sorted_display_list[
start_index : start_index + setting_help_max_contexts_per_page.get()
start_index : start_index + settings.get("user.help_max_contexts_per_page")
]
)

Expand Down Expand Up @@ -150,9 +152,8 @@ def get_pages(item_line_counts: list[int]) -> list[int]:
current_page = 1
pages = []
for line_count in item_line_counts:
if (
line_count + current_page_line_count
> setting_help_max_command_lines_per_page.get()
if line_count + current_page_line_count > settings.get(
"user.help_max_command_lines_per_page"
):
if current_page_line_count == 0:
# Special case, render a larger page.
Expand Down Expand Up @@ -468,7 +469,7 @@ def hide_all_help_guis():


def paginate_list(data, SIZE=None):
chunk_size = SIZE or setting_help_max_command_lines_per_page.get()
chunk_size = SIZE or settings.get("user.help_max_command_lines_per_page")
it = iter(data)
for i in range(0, len(data), chunk_size):
yield {k: data[k] for k in islice(it, chunk_size)}
Expand Down Expand Up @@ -630,16 +631,17 @@ def help_select_index(index: int):
"""Select the context by a number"""
global sorted_display_list, selected_context
if gui_context_help.showing:
if index < setting_help_max_contexts_per_page.get() and (
(current_context_page - 1) * setting_help_max_contexts_per_page.get()
if index < settings.get("user.help_max_contexts_per_page") and (
(current_context_page - 1)
* settings.get("user.help_max_contexts_per_page")
+ index
< len(sorted_display_list)
):
if selected_context is None:
selected_context = display_name_to_context_name_map[
sorted_display_list[
(current_context_page - 1)
* setting_help_max_contexts_per_page.get()
* settings.get("user.help_max_contexts_per_page")
+ index
]
]
Expand Down
9 changes: 5 additions & 4 deletions core/help/help_scope.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
from talon import Context, Module, actions, imgui, scope, ui
from talon import Context, Module, actions, imgui, scope, settings, ui

ctx = Context()
mod = Module()
mod.tag("help_scope_open", "tag for showing the scope help gui")

setting_max_length = mod.setting(
mod.setting(
"help_scope_max_length",
type=int,
default=50,
Expand Down Expand Up @@ -52,8 +52,9 @@ def print_value(gui: imgui.GUI, path: str, value, ignore: set[str] = {}):
def format_value(value):
if isinstance(value, (list, set)):
value = ", ".join(sorted(value))
if isinstance(value, str) and len(value) > setting_max_length.get() + 4:
return f"{value[:setting_max_length.get()]} ..."
setting_max_length = settings.get("user.help_scope_max_length")
if isinstance(value, str) and len(value) > setting_max_length + 4:
return f"{value[:setting_max_length]} ..."
return value


Expand Down
12 changes: 6 additions & 6 deletions core/mouse_grid/mouse_grid.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@
from talon.types.point import Point2d

mod = Module()
narrow_expansion = mod.setting(
mod.setting(
"grid_narrow_expansion",
type=int,
default=0,
desc="""After narrowing, grow the new region by this many pixels in every direction, to make things immediately on edges easier to hit, and when the grid is at its smallest, it allows you to still nudge it around""",
)
grids_put_one_bottom_left = mod.setting(
mod.setting(
"grids_put_one_bottom_left",
type=bool,
default=False,
Expand All @@ -24,7 +24,7 @@
mod.tag("mouse_grid_showing", desc="Tag indicates whether the mouse grid is showing")
mod.tag(
"mouse_grid_enabled",
desc="Deprecated: do not use. Activates legacy m grid command",
desc="Deprecated: do not use. Activates legacy m grid command",
)
ctx = Context()

Expand Down Expand Up @@ -152,7 +152,7 @@ def draw_text(offset_x, offset_y, width, height):
for row in range(3):
for col in range(3):
text_string = ""
if settings["user.grids_put_one_bottom_left"]:
if settings.get("user.grids_put_one_bottom_left"):
text_string = f"{(2 - row)*3+col+1}"
else:
text_string = f"{row*3+col+1}"
Expand Down Expand Up @@ -207,10 +207,10 @@ def draw_text(offset_x, offset_y, width, height):

def calc_narrow(self, which, rect):
rect = rect.copy()
bdr = narrow_expansion.get()
bdr = settings.get("user.grid_narrow_expansion")
row = int(which - 1) // 3
col = int(which - 1) % 3
if settings["user.grids_put_one_bottom_left"]:
if settings.get("user.grids_put_one_bottom_left"):
row = 2 - row
rect.x += int(col * rect.width // 3) - bdr
rect.y += int(row * rect.height // 3) - bdr
Expand Down
13 changes: 7 additions & 6 deletions core/snippets/snippets.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from collections import defaultdict
from pathlib import Path

from talon import Context, Module, actions, app, fs
from talon import Context, Module, actions, app, fs, settings

from ..modes.language_modes import language_ids
from .snippet_types import Snippet
Expand All @@ -16,11 +16,11 @@
mod.list("snippet_with_phrase", "List of insertion snippets containing a text phrase")
mod.list("snippet_wrapper", "List of wrapper snippets")

setting_dir = mod.setting(
mod.setting(
"snippets_dir",
str,
desc="Directory(relative to Talon user) containing additional snippets",
type=str,
default=None,
desc="Directory (relative to Talon user) containing additional snippets",
)

context_map = {
Expand All @@ -37,10 +37,11 @@


def get_setting_dir():
if not setting_dir.get():
setting_dir = settings.get("user.snippets_dir")
if not setting_dir:
return None

dir = Path(setting_dir.get())
dir = Path(setting_dir)

if not dir.is_absolute():
user_dir = Path(actions.path.talon_user())
Expand Down
6 changes: 3 additions & 3 deletions core/text/text_and_dictation.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@
import re
from typing import Callable, Optional

from talon import Context, Module, actions, grammar, ui
from talon import Context, Module, actions, grammar, settings, ui

mod = Module()

setting_context_sensitive_dictation = mod.setting(
mod.setting(
"context_sensitive_dictation",
type=bool,
default=False,
Expand Down Expand Up @@ -375,7 +375,7 @@ def dictation_insert_raw(text: str):
def dictation_insert(text: str, auto_cap: bool = True) -> str:
"""Inserts dictated text, formatted appropriately."""
add_space_after = False
if setting_context_sensitive_dictation.get():
if settings.get("user.context_sensitive_dictation"):
# Peek left if we might need leading space or auto-capitalization;
# peek right if we might need trailing space. NB. We peek right
# BEFORE insertion to avoid breaking the undo-chain between the
Expand Down
6 changes: 3 additions & 3 deletions core/windows_and_tabs/window_snap.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,14 @@
import logging
from typing import Optional

from talon import Context, Module, actions, ui
from talon import Context, Module, actions, settings, ui

mod = Module()
mod.list(
"window_snap_positions",
"Predefined window positions for the current window. See `RelativeScreenPos`.",
)
setting_window_snap_screen = mod.setting(
mod.setting(
"window_snap_screen",
type=str,
default="proportional",
Expand Down Expand Up @@ -116,7 +116,7 @@ def _move_to_screen(

dest = dest_screen.visible_rect
src = src_screen.visible_rect
how = setting_window_snap_screen.get()
how = settings.get("user.window_snap_screen")
if how == "size aware":
r = window.rect
left, right = interpolate_interval(
Expand Down
10 changes: 5 additions & 5 deletions plugin/command_history/command_history.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,8 @@
# We keep command_history_size lines of history, but by default display only
# command_history_display of them.
mod = Module()
setting_command_history_size = mod.setting("command_history_size", int, default=50)
setting_command_history_display = mod.setting(
"command_history_display", int, default=10
)
mod.setting("command_history_size", type=int, default=50)
mod.setting("command_history_display", type=int, default=10)

hist_more = False
history = []
Expand All @@ -33,7 +31,9 @@ def gui(gui: imgui.GUI):
gui.text("Command History")
gui.line()
text = (
history[:] if hist_more else history[-setting_command_history_display.get() :]
history[:]
if hist_more
else history[-settings.get("user.command_history_display") :]
)
for line in text:
gui.text(line)
Expand Down
6 changes: 3 additions & 3 deletions plugin/draft_editor/draft_editor.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from talon import Context, Module, actions, ui
from talon import Context, Module, actions, settings, ui

mod = Module()
mod.tag("draft_editor_active", "Indicates whether the draft editor has been activated")
Expand All @@ -23,7 +23,7 @@ def remove_tag(tag: str):

default_names = ["Visual Studio Code", "Code", "VSCodium", "Codium", "code-oss"]

setting_editor_names = mod.setting(
mod.setting(
"draft_editor",
type=str,
default=None,
Expand All @@ -32,7 +32,7 @@ def remove_tag(tag: str):


def get_editor_names():
names_csv = setting_editor_names.get()
names_csv = settings.get("user.draft_editor")
return names_csv.split(", ") if names_csv else default_names


Expand Down
Loading

0 comments on commit d904b4b

Please sign in to comment.