body_hash stringlengths 64 64 | body stringlengths 23 109k | docstring stringlengths 1 57k | path stringlengths 4 198 | name stringlengths 1 115 | repository_name stringlengths 7 111 | repository_stars float64 0 191k | lang stringclasses 1 value | body_without_docstring stringlengths 14 108k | unified stringlengths 45 133k |
|---|---|---|---|---|---|---|---|---|---|
21d500508c750b9e33575355a5cc775a58d5e8b45cd3e9dd2abb95316ac1f21e | def get_state_from_frame(self, frame_info):
'\n For stanford dataset\n '
self.obstacles = []
for element in frame_info:
if (element[6] != str(1)):
if (int(element[0]) != self.cur_ped):
left = int(element[1])
top = int(element[2])
width = (int(element[3]) - left)
height = (int(element[4]) - top)
self.obstacles.append(np.array([int((top + (height / 2))), int((left + (width / 2)))]))
else:
left = int(element[1])
top = int(element[2])
width = (int(element[3]) - left)
height = (int(element[4]) - top)
self.agent_state = np.array([int((top + (height / 2))), int((left + (width / 2)))]) | For stanford dataset | envs/gridworld_drone.py | get_state_from_frame | ranok92/deepirl | 2 | python | def get_state_from_frame(self, frame_info):
'\n \n '
self.obstacles = []
for element in frame_info:
if (element[6] != str(1)):
if (int(element[0]) != self.cur_ped):
left = int(element[1])
top = int(element[2])
width = (int(element[3]) - left)
height = (int(element[4]) - top)
self.obstacles.append(np.array([int((top + (height / 2))), int((left + (width / 2)))]))
else:
left = int(element[1])
top = int(element[2])
width = (int(element[3]) - left)
height = (int(element[4]) - top)
self.agent_state = np.array([int((top + (height / 2))), int((left + (width / 2)))]) | def get_state_from_frame(self, frame_info):
'\n \n '
self.obstacles = []
for element in frame_info:
if (element[6] != str(1)):
if (int(element[0]) != self.cur_ped):
left = int(element[1])
top = int(element[2])
width = (int(element[3]) - left)
height = (int(element[4]) - top)
self.obstacles.append(np.array([int((top + (height / 2))), int((left + (width / 2)))]))
else:
left = int(element[1])
top = int(element[2])
width = (int(element[3]) - left)
height = (int(element[4]) - top)
self.agent_state = np.array([int((top + (height / 2))), int((left + (width / 2)))])<|docstring|>For stanford dataset<|endoftext|> |
5ebabd536c65b5fa85eb61febcc97ba131bb03be1354c7bd10d9e6a6cc40e33f | def step(self, action=None):
'\n if external_control: t\n the state of the agent is updated based on the current action. \n else:\n the state of the agent is updated based on the information from the frames\n\n the rest of the actions, like calculating reward and checking if the episode is done remains as usual.\n '
self.current_frame += 1
if (str(self.current_frame) in self.annotation_dict.keys()):
self.get_state_from_frame_universal(self.annotation_dict[str(self.current_frame)])
if self.external_control:
if (not self.release_control):
if (action is not None):
if (not self.continuous_action):
action_orient = int((action % len(self.orientation_array)))
action_speed = int((action / len(self.orientation_array)))
orient_change = self.orientation_array[action_orient]
speed_change = self.speed_array[action_speed]
else:
speed_change = action[0]
orient_change = action[1]
self.cur_heading_dir = ((self.cur_heading_dir + orient_change) % 360)
agent_cur_speed = max(0, min((self.agent_state['speed'] + speed_change), self.max_speed))
prev_position = self.agent_state['position']
rot_mat = get_rot_matrix(deg_to_rad((- self.cur_heading_dir)))
cur_displacement = np.matmul(rot_mat, np.array([(- agent_cur_speed), 0]))
'\n cur_displacement is a 2 dim vector where the displacement is in the form:\n [row, col]\n '
self.agent_state['position'] = np.maximum(np.minimum((self.agent_state['position'] + cur_displacement), self.upper_limit_agent), self.lower_limit_agent)
self.agent_state['speed'] = agent_cur_speed
self.agent_state['orientation'] = np.matmul(rot_mat, np.array([(- 1), 0]))
self.heading_dir_history.append(self.cur_heading_dir)
self.pos_history.append((utils.copy_dict(self.agent_state), self.current_frame))
if self.ghost:
self.ghost_state_history.append((utils.copy_dict(self.ghost_state), self.current_frame))
(reward, done) = self.calculate_reward(action)
self.prev_action = action
if self.display:
self.render()
if (not self.release_control):
self.state['agent_state'] = utils.copy_dict(self.agent_state)
self.state['agent_head_dir'] = self.cur_heading_dir
self.state['ghost_state'] = utils.copy_dict(self.ghost_state)
if self.external_control:
if done:
self.release_control = True
return (self.state, reward, done, None) | if external_control: t
the state of the agent is updated based on the current action.
else:
the state of the agent is updated based on the information from the frames
the rest of the actions, like calculating reward and checking if the episode is done remains as usual. | envs/gridworld_drone.py | step | ranok92/deepirl | 2 | python | def step(self, action=None):
'\n if external_control: t\n the state of the agent is updated based on the current action. \n else:\n the state of the agent is updated based on the information from the frames\n\n the rest of the actions, like calculating reward and checking if the episode is done remains as usual.\n '
self.current_frame += 1
if (str(self.current_frame) in self.annotation_dict.keys()):
self.get_state_from_frame_universal(self.annotation_dict[str(self.current_frame)])
if self.external_control:
if (not self.release_control):
if (action is not None):
if (not self.continuous_action):
action_orient = int((action % len(self.orientation_array)))
action_speed = int((action / len(self.orientation_array)))
orient_change = self.orientation_array[action_orient]
speed_change = self.speed_array[action_speed]
else:
speed_change = action[0]
orient_change = action[1]
self.cur_heading_dir = ((self.cur_heading_dir + orient_change) % 360)
agent_cur_speed = max(0, min((self.agent_state['speed'] + speed_change), self.max_speed))
prev_position = self.agent_state['position']
rot_mat = get_rot_matrix(deg_to_rad((- self.cur_heading_dir)))
cur_displacement = np.matmul(rot_mat, np.array([(- agent_cur_speed), 0]))
'\n cur_displacement is a 2 dim vector where the displacement is in the form:\n [row, col]\n '
self.agent_state['position'] = np.maximum(np.minimum((self.agent_state['position'] + cur_displacement), self.upper_limit_agent), self.lower_limit_agent)
self.agent_state['speed'] = agent_cur_speed
self.agent_state['orientation'] = np.matmul(rot_mat, np.array([(- 1), 0]))
self.heading_dir_history.append(self.cur_heading_dir)
self.pos_history.append((utils.copy_dict(self.agent_state), self.current_frame))
if self.ghost:
self.ghost_state_history.append((utils.copy_dict(self.ghost_state), self.current_frame))
(reward, done) = self.calculate_reward(action)
self.prev_action = action
if self.display:
self.render()
if (not self.release_control):
self.state['agent_state'] = utils.copy_dict(self.agent_state)
self.state['agent_head_dir'] = self.cur_heading_dir
self.state['ghost_state'] = utils.copy_dict(self.ghost_state)
if self.external_control:
if done:
self.release_control = True
return (self.state, reward, done, None) | def step(self, action=None):
'\n if external_control: t\n the state of the agent is updated based on the current action. \n else:\n the state of the agent is updated based on the information from the frames\n\n the rest of the actions, like calculating reward and checking if the episode is done remains as usual.\n '
self.current_frame += 1
if (str(self.current_frame) in self.annotation_dict.keys()):
self.get_state_from_frame_universal(self.annotation_dict[str(self.current_frame)])
if self.external_control:
if (not self.release_control):
if (action is not None):
if (not self.continuous_action):
action_orient = int((action % len(self.orientation_array)))
action_speed = int((action / len(self.orientation_array)))
orient_change = self.orientation_array[action_orient]
speed_change = self.speed_array[action_speed]
else:
speed_change = action[0]
orient_change = action[1]
self.cur_heading_dir = ((self.cur_heading_dir + orient_change) % 360)
agent_cur_speed = max(0, min((self.agent_state['speed'] + speed_change), self.max_speed))
prev_position = self.agent_state['position']
rot_mat = get_rot_matrix(deg_to_rad((- self.cur_heading_dir)))
cur_displacement = np.matmul(rot_mat, np.array([(- agent_cur_speed), 0]))
'\n cur_displacement is a 2 dim vector where the displacement is in the form:\n [row, col]\n '
self.agent_state['position'] = np.maximum(np.minimum((self.agent_state['position'] + cur_displacement), self.upper_limit_agent), self.lower_limit_agent)
self.agent_state['speed'] = agent_cur_speed
self.agent_state['orientation'] = np.matmul(rot_mat, np.array([(- 1), 0]))
self.heading_dir_history.append(self.cur_heading_dir)
self.pos_history.append((utils.copy_dict(self.agent_state), self.current_frame))
if self.ghost:
self.ghost_state_history.append((utils.copy_dict(self.ghost_state), self.current_frame))
(reward, done) = self.calculate_reward(action)
self.prev_action = action
if self.display:
self.render()
if (not self.release_control):
self.state['agent_state'] = utils.copy_dict(self.agent_state)
self.state['agent_head_dir'] = self.cur_heading_dir
self.state['ghost_state'] = utils.copy_dict(self.ghost_state)
if self.external_control:
if done:
self.release_control = True
return (self.state, reward, done, None)<|docstring|>if external_control: t
the state of the agent is updated based on the current action.
else:
the state of the agent is updated based on the information from the frames
the rest of the actions, like calculating reward and checking if the episode is done remains as usual.<|endoftext|> |
5087ec71df971250e1814ecb56d64426ae5969e5f65eff3a88900dc773b26d11 | def reset(self, ped=None):
'\n Resets the environment, starting the obstacles from the start.\n If subject is specified, then the initial frame and final frame is set\n to the time frame when the subject is in the scene.\n\n If no subject is specified then the initial frame is set to the overall\n initial frame and goes till the last frame available in the annotation file.\n\n Also, the agent and goal positions are initialized at random.\n\n Pro tip: Use this function while training the agent.\n '
if self.replace_subject:
return self.reset_and_replace(ped)
else:
self.current_frame = self.initial_frame
self.pos_history = []
self.ghost_state_history = []
dist_g = self.goal_spawn_clearance
if self.annotation_file:
self.get_state_from_frame_universal(self.annotation_dict[str(self.current_frame)])
num_obs = len(self.obstacles)
if (self.cur_ped is None):
while True:
flag = False
self.goal_state = np.asarray([np.random.randint(self.lower_limit_goal[0], self.upper_limit_goal[0]), np.random.randint(self.lower_limit_goal[1], self.upper_limit_goal[1])])
for i in range(num_obs):
if (np.linalg.norm((self.obstacles[i]['position'] - self.goal_state)) < dist_g):
flag = True
if (not flag):
break
dist = self.agent_spawn_clearance
while True:
flag = False
self.agent_state['position'] = np.asarray([np.random.randint(self.lower_limit_agent[0], self.upper_limit_agent[0]), np.random.randint(self.lower_limit_agent[1], self.upper_limit_agent[1])])
for i in range(num_obs):
if (np.linalg.norm((self.obstacles[i]['position'] - self.agent_state['position'])) < dist):
flag = True
if (not flag):
break
self.agent_state['speed'] = 0
self.cur_heading_dir = 0
self.agent_state['orientation'] = np.matmul(get_rot_matrix(deg_to_rad(self.cur_heading_dir)), np.array([self.agent_state['speed'], 0]))
self.release_control = False
self.state = {}
self.state['agent_state'] = utils.copy_dict(self.agent_state)
self.state['agent_head_dir'] = self.cur_heading_dir
self.state['goal_state'] = self.goal_state
self.state['release_control'] = self.release_control
self.state['obstacles'] = self.obstacles
self.pos_history.append((utils.copy_dict(self.agent_state), self.current_frame))
if self.ghost:
self.ghost_state_history.append((utils.copy_dict(self.ghost_state), self.current_frame))
self.state['ghost_state'] = utils.copy_dict(self.ghost_state)
self.distanceFromgoal = np.linalg.norm((self.agent_state['position'] - self.goal_state), 1)
self.cur_heading_dir = 0
self.heading_dir_history = []
self.heading_dir_history.append(self.cur_heading_dir)
pygame.display.set_caption('Your not so friendly continuous environment')
if self.display:
self.render()
return self.state | Resets the environment, starting the obstacles from the start.
If subject is specified, then the initial frame and final frame is set
to the time frame when the subject is in the scene.
If no subject is specified then the initial frame is set to the overall
initial frame and goes till the last frame available in the annotation file.
Also, the agent and goal positions are initialized at random.
Pro tip: Use this function while training the agent. | envs/gridworld_drone.py | reset | ranok92/deepirl | 2 | python | def reset(self, ped=None):
'\n Resets the environment, starting the obstacles from the start.\n If subject is specified, then the initial frame and final frame is set\n to the time frame when the subject is in the scene.\n\n If no subject is specified then the initial frame is set to the overall\n initial frame and goes till the last frame available in the annotation file.\n\n Also, the agent and goal positions are initialized at random.\n\n Pro tip: Use this function while training the agent.\n '
if self.replace_subject:
return self.reset_and_replace(ped)
else:
self.current_frame = self.initial_frame
self.pos_history = []
self.ghost_state_history = []
dist_g = self.goal_spawn_clearance
if self.annotation_file:
self.get_state_from_frame_universal(self.annotation_dict[str(self.current_frame)])
num_obs = len(self.obstacles)
if (self.cur_ped is None):
while True:
flag = False
self.goal_state = np.asarray([np.random.randint(self.lower_limit_goal[0], self.upper_limit_goal[0]), np.random.randint(self.lower_limit_goal[1], self.upper_limit_goal[1])])
for i in range(num_obs):
if (np.linalg.norm((self.obstacles[i]['position'] - self.goal_state)) < dist_g):
flag = True
if (not flag):
break
dist = self.agent_spawn_clearance
while True:
flag = False
self.agent_state['position'] = np.asarray([np.random.randint(self.lower_limit_agent[0], self.upper_limit_agent[0]), np.random.randint(self.lower_limit_agent[1], self.upper_limit_agent[1])])
for i in range(num_obs):
if (np.linalg.norm((self.obstacles[i]['position'] - self.agent_state['position'])) < dist):
flag = True
if (not flag):
break
self.agent_state['speed'] = 0
self.cur_heading_dir = 0
self.agent_state['orientation'] = np.matmul(get_rot_matrix(deg_to_rad(self.cur_heading_dir)), np.array([self.agent_state['speed'], 0]))
self.release_control = False
self.state = {}
self.state['agent_state'] = utils.copy_dict(self.agent_state)
self.state['agent_head_dir'] = self.cur_heading_dir
self.state['goal_state'] = self.goal_state
self.state['release_control'] = self.release_control
self.state['obstacles'] = self.obstacles
self.pos_history.append((utils.copy_dict(self.agent_state), self.current_frame))
if self.ghost:
self.ghost_state_history.append((utils.copy_dict(self.ghost_state), self.current_frame))
self.state['ghost_state'] = utils.copy_dict(self.ghost_state)
self.distanceFromgoal = np.linalg.norm((self.agent_state['position'] - self.goal_state), 1)
self.cur_heading_dir = 0
self.heading_dir_history = []
self.heading_dir_history.append(self.cur_heading_dir)
pygame.display.set_caption('Your not so friendly continuous environment')
if self.display:
self.render()
return self.state | def reset(self, ped=None):
'\n Resets the environment, starting the obstacles from the start.\n If subject is specified, then the initial frame and final frame is set\n to the time frame when the subject is in the scene.\n\n If no subject is specified then the initial frame is set to the overall\n initial frame and goes till the last frame available in the annotation file.\n\n Also, the agent and goal positions are initialized at random.\n\n Pro tip: Use this function while training the agent.\n '
if self.replace_subject:
return self.reset_and_replace(ped)
else:
self.current_frame = self.initial_frame
self.pos_history = []
self.ghost_state_history = []
dist_g = self.goal_spawn_clearance
if self.annotation_file:
self.get_state_from_frame_universal(self.annotation_dict[str(self.current_frame)])
num_obs = len(self.obstacles)
if (self.cur_ped is None):
while True:
flag = False
self.goal_state = np.asarray([np.random.randint(self.lower_limit_goal[0], self.upper_limit_goal[0]), np.random.randint(self.lower_limit_goal[1], self.upper_limit_goal[1])])
for i in range(num_obs):
if (np.linalg.norm((self.obstacles[i]['position'] - self.goal_state)) < dist_g):
flag = True
if (not flag):
break
dist = self.agent_spawn_clearance
while True:
flag = False
self.agent_state['position'] = np.asarray([np.random.randint(self.lower_limit_agent[0], self.upper_limit_agent[0]), np.random.randint(self.lower_limit_agent[1], self.upper_limit_agent[1])])
for i in range(num_obs):
if (np.linalg.norm((self.obstacles[i]['position'] - self.agent_state['position'])) < dist):
flag = True
if (not flag):
break
self.agent_state['speed'] = 0
self.cur_heading_dir = 0
self.agent_state['orientation'] = np.matmul(get_rot_matrix(deg_to_rad(self.cur_heading_dir)), np.array([self.agent_state['speed'], 0]))
self.release_control = False
self.state = {}
self.state['agent_state'] = utils.copy_dict(self.agent_state)
self.state['agent_head_dir'] = self.cur_heading_dir
self.state['goal_state'] = self.goal_state
self.state['release_control'] = self.release_control
self.state['obstacles'] = self.obstacles
self.pos_history.append((utils.copy_dict(self.agent_state), self.current_frame))
if self.ghost:
self.ghost_state_history.append((utils.copy_dict(self.ghost_state), self.current_frame))
self.state['ghost_state'] = utils.copy_dict(self.ghost_state)
self.distanceFromgoal = np.linalg.norm((self.agent_state['position'] - self.goal_state), 1)
self.cur_heading_dir = 0
self.heading_dir_history = []
self.heading_dir_history.append(self.cur_heading_dir)
pygame.display.set_caption('Your not so friendly continuous environment')
if self.display:
self.render()
return self.state<|docstring|>Resets the environment, starting the obstacles from the start.
If subject is specified, then the initial frame and final frame is set
to the time frame when the subject is in the scene.
If no subject is specified then the initial frame is set to the overall
initial frame and goes till the last frame available in the annotation file.
Also, the agent and goal positions are initialized at random.
Pro tip: Use this function while training the agent.<|endoftext|> |
50e9d56e365ab06d6c193807d78322e32f8051e195c52c6a24e9410aca49e40b | def reset_and_replace(self, ped=None):
'\n Resets the environment and replaces one of the existing pedestrians\n from the video feed in the environment with the agent.\n Pro tip: Use this for testing the result.\n '
no_of_peds = len(self.pedestrian_dict.keys())
if (self.subject is None):
while True:
if (ped is not None):
while (str(ped) not in self.pedestrian_dict.keys()):
ped += 1
self.cur_ped = ped
break
else:
if self.is_random:
self.cur_ped = np.random.randint(1, (no_of_peds + 1))
elif ((self.cur_ped is None) or (self.cur_ped == self.last_pedestrian)):
self.cur_ped = 1
else:
self.cur_ped += 1
if (str(self.cur_ped) in self.pedestrian_dict.keys()):
break
else:
self.cur_ped = self.subject
if self.show_comparison:
self.ghost = self.cur_ped
self.skip_list = []
self.skip_list.append(self.cur_ped)
if (self.segment_size is None):
self.current_frame = int(self.pedestrian_dict[str(self.cur_ped)]['initial_frame'])
self.final_frame = int(self.pedestrian_dict[str(self.cur_ped)]['final_frame'])
self.goal_state = self.pedestrian_dict[str(self.cur_ped)][str(self.final_frame)]['position']
else:
first_frame = int(self.pedestrian_dict[str(self.cur_ped)]['initial_frame'])
final_frame = int(self.pedestrian_dict[str(self.cur_ped)]['final_frame'])
total_frames = (final_frame - first_frame)
total_segments = (int((total_frames / self.segment_size)) + 1)
cur_segment = np.random.randint(total_segments)
self.current_frame = (first_frame + (cur_segment * self.segment_size))
self.final_frame = min((self.current_frame + self.segment_size), final_frame)
self.goal_state = self.pedestrian_dict[str(self.cur_ped)][str(self.final_frame)]['position']
self.get_state_from_frame_universal(self.annotation_dict[str(self.current_frame)])
self.agent_state = utils.copy_dict(self.pedestrian_dict[str(self.cur_ped)][str(self.current_frame)])
self.agent_state['speed'] = 0
self.cur_heading_dir = 0
self.agent_state['orientation'] = np.matmul(get_rot_matrix(deg_to_rad(self.cur_heading_dir)), np.array([(- 1), 0]))
self.release_control = False
self.state = {}
self.state['agent_state'] = utils.copy_dict(self.agent_state)
self.state['agent_head_dir'] = self.cur_heading_dir
self.state['goal_state'] = self.goal_state
self.state['release_control'] = self.release_control
self.state['obstacles'] = self.obstacles
self.pos_history = []
self.pos_history.append((utils.copy_dict(self.agent_state), self.current_frame))
if self.ghost:
self.ghost_state_history = []
self.ghost_state = utils.copy_dict(self.agent_state)
self.ghost_state_history.append((utils.copy_dict(self.ghost_state), self.current_frame))
if self.ghost:
self.ghost_state_history = []
self.ghost_state = utils.copy_dict(self.agent_state)
self.ghost_state_history.append((utils.copy_dict(self.ghost_state), self.current_frame))
self.state['ghost_state'] = utils.copy_dict(self.ghost_state)
self.distanceFromgoal = np.linalg.norm((self.agent_state['position'] - self.goal_state), 1)
self.heading_dir_history = []
self.heading_dir_history.append(self.cur_heading_dir)
if self.display:
pygame.display.set_caption('Your not so friendly continuous environment')
self.render()
return self.state | Resets the environment and replaces one of the existing pedestrians
from the video feed in the environment with the agent.
Pro tip: Use this for testing the result. | envs/gridworld_drone.py | reset_and_replace | ranok92/deepirl | 2 | python | def reset_and_replace(self, ped=None):
'\n Resets the environment and replaces one of the existing pedestrians\n from the video feed in the environment with the agent.\n Pro tip: Use this for testing the result.\n '
no_of_peds = len(self.pedestrian_dict.keys())
if (self.subject is None):
while True:
if (ped is not None):
while (str(ped) not in self.pedestrian_dict.keys()):
ped += 1
self.cur_ped = ped
break
else:
if self.is_random:
self.cur_ped = np.random.randint(1, (no_of_peds + 1))
elif ((self.cur_ped is None) or (self.cur_ped == self.last_pedestrian)):
self.cur_ped = 1
else:
self.cur_ped += 1
if (str(self.cur_ped) in self.pedestrian_dict.keys()):
break
else:
self.cur_ped = self.subject
if self.show_comparison:
self.ghost = self.cur_ped
self.skip_list = []
self.skip_list.append(self.cur_ped)
if (self.segment_size is None):
self.current_frame = int(self.pedestrian_dict[str(self.cur_ped)]['initial_frame'])
self.final_frame = int(self.pedestrian_dict[str(self.cur_ped)]['final_frame'])
self.goal_state = self.pedestrian_dict[str(self.cur_ped)][str(self.final_frame)]['position']
else:
first_frame = int(self.pedestrian_dict[str(self.cur_ped)]['initial_frame'])
final_frame = int(self.pedestrian_dict[str(self.cur_ped)]['final_frame'])
total_frames = (final_frame - first_frame)
total_segments = (int((total_frames / self.segment_size)) + 1)
cur_segment = np.random.randint(total_segments)
self.current_frame = (first_frame + (cur_segment * self.segment_size))
self.final_frame = min((self.current_frame + self.segment_size), final_frame)
self.goal_state = self.pedestrian_dict[str(self.cur_ped)][str(self.final_frame)]['position']
self.get_state_from_frame_universal(self.annotation_dict[str(self.current_frame)])
self.agent_state = utils.copy_dict(self.pedestrian_dict[str(self.cur_ped)][str(self.current_frame)])
self.agent_state['speed'] = 0
self.cur_heading_dir = 0
self.agent_state['orientation'] = np.matmul(get_rot_matrix(deg_to_rad(self.cur_heading_dir)), np.array([(- 1), 0]))
self.release_control = False
self.state = {}
self.state['agent_state'] = utils.copy_dict(self.agent_state)
self.state['agent_head_dir'] = self.cur_heading_dir
self.state['goal_state'] = self.goal_state
self.state['release_control'] = self.release_control
self.state['obstacles'] = self.obstacles
self.pos_history = []
self.pos_history.append((utils.copy_dict(self.agent_state), self.current_frame))
if self.ghost:
self.ghost_state_history = []
self.ghost_state = utils.copy_dict(self.agent_state)
self.ghost_state_history.append((utils.copy_dict(self.ghost_state), self.current_frame))
if self.ghost:
self.ghost_state_history = []
self.ghost_state = utils.copy_dict(self.agent_state)
self.ghost_state_history.append((utils.copy_dict(self.ghost_state), self.current_frame))
self.state['ghost_state'] = utils.copy_dict(self.ghost_state)
self.distanceFromgoal = np.linalg.norm((self.agent_state['position'] - self.goal_state), 1)
self.heading_dir_history = []
self.heading_dir_history.append(self.cur_heading_dir)
if self.display:
pygame.display.set_caption('Your not so friendly continuous environment')
self.render()
return self.state | def reset_and_replace(self, ped=None):
'\n Resets the environment and replaces one of the existing pedestrians\n from the video feed in the environment with the agent.\n Pro tip: Use this for testing the result.\n '
no_of_peds = len(self.pedestrian_dict.keys())
if (self.subject is None):
while True:
if (ped is not None):
while (str(ped) not in self.pedestrian_dict.keys()):
ped += 1
self.cur_ped = ped
break
else:
if self.is_random:
self.cur_ped = np.random.randint(1, (no_of_peds + 1))
elif ((self.cur_ped is None) or (self.cur_ped == self.last_pedestrian)):
self.cur_ped = 1
else:
self.cur_ped += 1
if (str(self.cur_ped) in self.pedestrian_dict.keys()):
break
else:
self.cur_ped = self.subject
if self.show_comparison:
self.ghost = self.cur_ped
self.skip_list = []
self.skip_list.append(self.cur_ped)
if (self.segment_size is None):
self.current_frame = int(self.pedestrian_dict[str(self.cur_ped)]['initial_frame'])
self.final_frame = int(self.pedestrian_dict[str(self.cur_ped)]['final_frame'])
self.goal_state = self.pedestrian_dict[str(self.cur_ped)][str(self.final_frame)]['position']
else:
first_frame = int(self.pedestrian_dict[str(self.cur_ped)]['initial_frame'])
final_frame = int(self.pedestrian_dict[str(self.cur_ped)]['final_frame'])
total_frames = (final_frame - first_frame)
total_segments = (int((total_frames / self.segment_size)) + 1)
cur_segment = np.random.randint(total_segments)
self.current_frame = (first_frame + (cur_segment * self.segment_size))
self.final_frame = min((self.current_frame + self.segment_size), final_frame)
self.goal_state = self.pedestrian_dict[str(self.cur_ped)][str(self.final_frame)]['position']
self.get_state_from_frame_universal(self.annotation_dict[str(self.current_frame)])
self.agent_state = utils.copy_dict(self.pedestrian_dict[str(self.cur_ped)][str(self.current_frame)])
self.agent_state['speed'] = 0
self.cur_heading_dir = 0
self.agent_state['orientation'] = np.matmul(get_rot_matrix(deg_to_rad(self.cur_heading_dir)), np.array([(- 1), 0]))
self.release_control = False
self.state = {}
self.state['agent_state'] = utils.copy_dict(self.agent_state)
self.state['agent_head_dir'] = self.cur_heading_dir
self.state['goal_state'] = self.goal_state
self.state['release_control'] = self.release_control
self.state['obstacles'] = self.obstacles
self.pos_history = []
self.pos_history.append((utils.copy_dict(self.agent_state), self.current_frame))
if self.ghost:
self.ghost_state_history = []
self.ghost_state = utils.copy_dict(self.agent_state)
self.ghost_state_history.append((utils.copy_dict(self.ghost_state), self.current_frame))
if self.ghost:
self.ghost_state_history = []
self.ghost_state = utils.copy_dict(self.agent_state)
self.ghost_state_history.append((utils.copy_dict(self.ghost_state), self.current_frame))
self.state['ghost_state'] = utils.copy_dict(self.ghost_state)
self.distanceFromgoal = np.linalg.norm((self.agent_state['position'] - self.goal_state), 1)
self.heading_dir_history = []
self.heading_dir_history.append(self.cur_heading_dir)
if self.display:
pygame.display.set_caption('Your not so friendly continuous environment')
self.render()
return self.state<|docstring|>Resets the environment and replaces one of the existing pedestrians
from the video feed in the environment with the agent.
Pro tip: Use this for testing the result.<|endoftext|> |
d90c5039f0a4877e556f1f3e17d55469da032cd53d9e60f776c737195e906e6b | def rollback(self, frames):
'\n Added this function primarily for reward analysis purpose.\n Provided the frames, this function rolls the environment back in time by the number of\n frames provided\n '
self.current_frame = (self.current_frame - frames)
if (str(self.current_frame) in self.annotation_dict.keys()):
self.get_state_from_frame_universal(self.annotation_dict[str(self.current_frame)])
if self.external_control:
self.agent_state = utils.copy_dict(self.pos_history[((- frames) - 1)])
self.cur_heading_dir = self.heading_dir_history[((- frames) - 1)]
if (frames > len(self.heading_dir_history)):
print('Trying to rollback more than the size of current history!')
else:
for i in range(1, (frames + 1)):
self.heading_dir_history.pop((- 1))
self.pos_history.pop((- 1))
if self.release_control:
self.release_control = False
self.state['agent_state'] = utils.copy_dict(self.agent_state)
if self.display:
self.render()
return self.state | Added this function primarily for reward analysis purpose.
Provided the frames, this function rolls the environment back in time by the number of
frames provided | envs/gridworld_drone.py | rollback | ranok92/deepirl | 2 | python | def rollback(self, frames):
'\n Added this function primarily for reward analysis purpose.\n Provided the frames, this function rolls the environment back in time by the number of\n frames provided\n '
self.current_frame = (self.current_frame - frames)
if (str(self.current_frame) in self.annotation_dict.keys()):
self.get_state_from_frame_universal(self.annotation_dict[str(self.current_frame)])
if self.external_control:
self.agent_state = utils.copy_dict(self.pos_history[((- frames) - 1)])
self.cur_heading_dir = self.heading_dir_history[((- frames) - 1)]
if (frames > len(self.heading_dir_history)):
print('Trying to rollback more than the size of current history!')
else:
for i in range(1, (frames + 1)):
self.heading_dir_history.pop((- 1))
self.pos_history.pop((- 1))
if self.release_control:
self.release_control = False
self.state['agent_state'] = utils.copy_dict(self.agent_state)
if self.display:
self.render()
return self.state | def rollback(self, frames):
'\n Added this function primarily for reward analysis purpose.\n Provided the frames, this function rolls the environment back in time by the number of\n frames provided\n '
self.current_frame = (self.current_frame - frames)
if (str(self.current_frame) in self.annotation_dict.keys()):
self.get_state_from_frame_universal(self.annotation_dict[str(self.current_frame)])
if self.external_control:
self.agent_state = utils.copy_dict(self.pos_history[((- frames) - 1)])
self.cur_heading_dir = self.heading_dir_history[((- frames) - 1)]
if (frames > len(self.heading_dir_history)):
print('Trying to rollback more than the size of current history!')
else:
for i in range(1, (frames + 1)):
self.heading_dir_history.pop((- 1))
self.pos_history.pop((- 1))
if self.release_control:
self.release_control = False
self.state['agent_state'] = utils.copy_dict(self.agent_state)
if self.display:
self.render()
return self.state<|docstring|>Added this function primarily for reward analysis purpose.
Provided the frames, this function rolls the environment back in time by the number of
frames provided<|endoftext|> |
1a5981f863f3a667d25efa765d9528bcc609f6b3ecd5ad4a2747b8b5998b7768 | def draw_trajectory(self, trajectory=[], color=None, show_frames=False):
'\n Draws a trajectory on the environment map based on the list of states provided\n in the trajectory list.\n input:\n trajectory : A list of tuples, where each tuple in the list consists of :\n (state dictionary, frame_id of that state)\n color : The color to draw the trajectory.\n\n show_frames : If none or int to specify the interval at which the trajectory \n will be annotated with the current frame. \n\n output: \n A line that traces the positions taken by the entity whose state history\n is provided in the trajectory variable.\n '
arrow_length = 1
arrow_head_width = 1
arrow_width = 0.1
font = pygame.freetype.Font(None, 10)
rad = int((self.cellWidth * 0.4))
start_pos = ((trajectory[0][0]['position'] + 0.5) * self.cellWidth)
end_pos = ((trajectory[(- 1)][0]['position'] + 0.5) * self.cellWidth)
start_frame = trajectory[0][1]
end_frame = trajectory[(- 1)][1]
pygame.draw.circle(self.gameDisplay, (0, 255, 0), (int(start_pos[1]), int(start_pos[0])), rad)
pygame.draw.circle(self.gameDisplay, (0, 0, 255), (int(end_pos[1]), int(end_pos[0])), rad)
font.render_to(self.gameDisplay, (((start_pos[1] - (self.obs_width / 2)) - 10), ((start_pos[0] - (self.obs_width / 2)) - 5)), str(start_frame), fgcolor=(0, 0, 0))
font.render_to(self.gameDisplay, (((end_pos[1] - (self.obs_width / 2)) - 10), ((end_pos[0] - (self.obs_width / 2)) - 5)), str(end_frame), fgcolor=(0, 0, 0))
current_frame = start_frame
for count in range((len(trajectory) - 1)):
if show_frames:
if ((count % show_frames) == 0):
cur_pos = trajectory[count][0]['position']
pygame.draw.circle(self.gameDisplay, (0, 0, 255), (int(cur_pos[1]), int(cur_pos[0])), 3)
font.render_to(self.gameDisplay, (((trajectory[count][0]['position'][1] - (self.obs_width / 2)) - 10), ((trajectory[count][0]['position'][0] - (self.obs_width / 2)) - 5)), str(current_frame), fgcolor=(0, 0, 0))
self.draw_arrow(trajectory[count][0]['position'], trajectory[(count + 1)][0]['position'], color)
current_frame = trajectory[count][1] | Draws a trajectory on the environment map based on the list of states provided
in the trajectory list.
input:
trajectory : A list of tuples, where each tuple in the list consists of :
(state dictionary, frame_id of that state)
color : The color to draw the trajectory.
show_frames : If none or int to specify the interval at which the trajectory
will be annotated with the current frame.
output:
A line that traces the positions taken by the entity whose state history
is provided in the trajectory variable. | envs/gridworld_drone.py | draw_trajectory | ranok92/deepirl | 2 | python | def draw_trajectory(self, trajectory=[], color=None, show_frames=False):
'\n Draws a trajectory on the environment map based on the list of states provided\n in the trajectory list.\n input:\n trajectory : A list of tuples, where each tuple in the list consists of :\n (state dictionary, frame_id of that state)\n color : The color to draw the trajectory.\n\n show_frames : If none or int to specify the interval at which the trajectory \n will be annotated with the current frame. \n\n output: \n A line that traces the positions taken by the entity whose state history\n is provided in the trajectory variable.\n '
arrow_length = 1
arrow_head_width = 1
arrow_width = 0.1
font = pygame.freetype.Font(None, 10)
rad = int((self.cellWidth * 0.4))
start_pos = ((trajectory[0][0]['position'] + 0.5) * self.cellWidth)
end_pos = ((trajectory[(- 1)][0]['position'] + 0.5) * self.cellWidth)
start_frame = trajectory[0][1]
end_frame = trajectory[(- 1)][1]
pygame.draw.circle(self.gameDisplay, (0, 255, 0), (int(start_pos[1]), int(start_pos[0])), rad)
pygame.draw.circle(self.gameDisplay, (0, 0, 255), (int(end_pos[1]), int(end_pos[0])), rad)
font.render_to(self.gameDisplay, (((start_pos[1] - (self.obs_width / 2)) - 10), ((start_pos[0] - (self.obs_width / 2)) - 5)), str(start_frame), fgcolor=(0, 0, 0))
font.render_to(self.gameDisplay, (((end_pos[1] - (self.obs_width / 2)) - 10), ((end_pos[0] - (self.obs_width / 2)) - 5)), str(end_frame), fgcolor=(0, 0, 0))
current_frame = start_frame
for count in range((len(trajectory) - 1)):
if show_frames:
if ((count % show_frames) == 0):
cur_pos = trajectory[count][0]['position']
pygame.draw.circle(self.gameDisplay, (0, 0, 255), (int(cur_pos[1]), int(cur_pos[0])), 3)
font.render_to(self.gameDisplay, (((trajectory[count][0]['position'][1] - (self.obs_width / 2)) - 10), ((trajectory[count][0]['position'][0] - (self.obs_width / 2)) - 5)), str(current_frame), fgcolor=(0, 0, 0))
self.draw_arrow(trajectory[count][0]['position'], trajectory[(count + 1)][0]['position'], color)
current_frame = trajectory[count][1] | def draw_trajectory(self, trajectory=[], color=None, show_frames=False):
'\n Draws a trajectory on the environment map based on the list of states provided\n in the trajectory list.\n input:\n trajectory : A list of tuples, where each tuple in the list consists of :\n (state dictionary, frame_id of that state)\n color : The color to draw the trajectory.\n\n show_frames : If none or int to specify the interval at which the trajectory \n will be annotated with the current frame. \n\n output: \n A line that traces the positions taken by the entity whose state history\n is provided in the trajectory variable.\n '
arrow_length = 1
arrow_head_width = 1
arrow_width = 0.1
font = pygame.freetype.Font(None, 10)
rad = int((self.cellWidth * 0.4))
start_pos = ((trajectory[0][0]['position'] + 0.5) * self.cellWidth)
end_pos = ((trajectory[(- 1)][0]['position'] + 0.5) * self.cellWidth)
start_frame = trajectory[0][1]
end_frame = trajectory[(- 1)][1]
pygame.draw.circle(self.gameDisplay, (0, 255, 0), (int(start_pos[1]), int(start_pos[0])), rad)
pygame.draw.circle(self.gameDisplay, (0, 0, 255), (int(end_pos[1]), int(end_pos[0])), rad)
font.render_to(self.gameDisplay, (((start_pos[1] - (self.obs_width / 2)) - 10), ((start_pos[0] - (self.obs_width / 2)) - 5)), str(start_frame), fgcolor=(0, 0, 0))
font.render_to(self.gameDisplay, (((end_pos[1] - (self.obs_width / 2)) - 10), ((end_pos[0] - (self.obs_width / 2)) - 5)), str(end_frame), fgcolor=(0, 0, 0))
current_frame = start_frame
for count in range((len(trajectory) - 1)):
if show_frames:
if ((count % show_frames) == 0):
cur_pos = trajectory[count][0]['position']
pygame.draw.circle(self.gameDisplay, (0, 0, 255), (int(cur_pos[1]), int(cur_pos[0])), 3)
font.render_to(self.gameDisplay, (((trajectory[count][0]['position'][1] - (self.obs_width / 2)) - 10), ((trajectory[count][0]['position'][0] - (self.obs_width / 2)) - 5)), str(current_frame), fgcolor=(0, 0, 0))
self.draw_arrow(trajectory[count][0]['position'], trajectory[(count + 1)][0]['position'], color)
current_frame = trajectory[count][1]<|docstring|>Draws a trajectory on the environment map based on the list of states provided
in the trajectory list.
input:
trajectory : A list of tuples, where each tuple in the list consists of :
(state dictionary, frame_id of that state)
color : The color to draw the trajectory.
show_frames : If none or int to specify the interval at which the trajectory
will be annotated with the current frame.
output:
A line that traces the positions taken by the entity whose state history
is provided in the trajectory variable.<|endoftext|> |
dfcbeb80bcb0c2cb81eaca8de69808e1c88eb8272efcf40ad4feb3fc9a1e8b66 | def take_screenshot(self):
'\n captures the current screen and returns a 3d array \n containing the pixel information\n '
return pygame.surfarray.array3d(self.gameDisplay) | captures the current screen and returns a 3d array
containing the pixel information | envs/gridworld_drone.py | take_screenshot | ranok92/deepirl | 2 | python | def take_screenshot(self):
'\n captures the current screen and returns a 3d array \n containing the pixel information\n '
return pygame.surfarray.array3d(self.gameDisplay) | def take_screenshot(self):
'\n captures the current screen and returns a 3d array \n containing the pixel information\n '
return pygame.surfarray.array3d(self.gameDisplay)<|docstring|>captures the current screen and returns a 3d array
containing the pixel information<|endoftext|> |
9a82118229ea55a5aa153c6bce01b51dbf75c33d5b60895e86a5ad9496c4826b | def ensure_file_exists(filename):
' expanduser ~ and convert to current folder if the parent folder does not exist.\n \n filename: Full path, e.g. ~/a.py\n '
newfile = os.path.expanduser(filename)
file_folder = os.path.dirname(newfile)
if (not os.path.exists(file_folder)):
newfile = os.path.basename(newfile)
return newfile | expanduser ~ and convert to current folder if the parent folder does not exist.
filename: Full path, e.g. ~/a.py | aws_vps_robot/pybot/changeStaticIP.py | ensure_file_exists | peterjpxie/All-in-One-VPN | 3 | python | def ensure_file_exists(filename):
' expanduser ~ and convert to current folder if the parent folder does not exist.\n \n filename: Full path, e.g. ~/a.py\n '
newfile = os.path.expanduser(filename)
file_folder = os.path.dirname(newfile)
if (not os.path.exists(file_folder)):
newfile = os.path.basename(newfile)
return newfile | def ensure_file_exists(filename):
' expanduser ~ and convert to current folder if the parent folder does not exist.\n \n filename: Full path, e.g. ~/a.py\n '
newfile = os.path.expanduser(filename)
file_folder = os.path.dirname(newfile)
if (not os.path.exists(file_folder)):
newfile = os.path.basename(newfile)
return newfile<|docstring|>expanduser ~ and convert to current folder if the parent folder does not exist.
filename: Full path, e.g. ~/a.py<|endoftext|> |
811dcbfd7e6bb89c5fae5e730bf41f553e9d76eac01147f190e31b2963e1c84a | def __init__(self, c, localFlag):
'Ctor for the ParserBaseClass class.'
self.c = c
self.clipBoard = []
self.localFlag = localFlag
self.shortcutsDict = g.TypedDict(name='parser.shortcutsDict', keyType=type('shortcutName'), valType=g.BindingInfo)
self.openWithList = []
self.dispatchDict = {'bool': self.doBool, 'buttons': self.doButtons, 'color': self.doColor, 'commands': self.doCommands, 'data': self.doData, 'directory': self.doDirectory, 'enabledplugins': self.doEnabledPlugins, 'font': self.doFont, 'ifenv': self.doIfEnv, 'ifhostname': self.doIfHostname, 'ifplatform': self.doIfPlatform, 'ignore': self.doIgnore, 'int': self.doInt, 'ints': self.doInts, 'float': self.doFloat, 'menus': self.doMenus, 'menuat': self.doMenuat, 'popup': self.doPopup, 'mode': self.doMode, 'openwith': self.doOpenWith, 'outlinedata': self.doOutlineData, 'path': self.doPath, 'ratio': self.doRatio, 'shortcuts': self.doShortcuts, 'string': self.doString, 'strings': self.doStrings}
self.debug_count = 0 | Ctor for the ParserBaseClass class. | leo/core/leoConfig.py | __init__ | thomasbuttler/leo-editor | 1,550 | python | def __init__(self, c, localFlag):
self.c = c
self.clipBoard = []
self.localFlag = localFlag
self.shortcutsDict = g.TypedDict(name='parser.shortcutsDict', keyType=type('shortcutName'), valType=g.BindingInfo)
self.openWithList = []
self.dispatchDict = {'bool': self.doBool, 'buttons': self.doButtons, 'color': self.doColor, 'commands': self.doCommands, 'data': self.doData, 'directory': self.doDirectory, 'enabledplugins': self.doEnabledPlugins, 'font': self.doFont, 'ifenv': self.doIfEnv, 'ifhostname': self.doIfHostname, 'ifplatform': self.doIfPlatform, 'ignore': self.doIgnore, 'int': self.doInt, 'ints': self.doInts, 'float': self.doFloat, 'menus': self.doMenus, 'menuat': self.doMenuat, 'popup': self.doPopup, 'mode': self.doMode, 'openwith': self.doOpenWith, 'outlinedata': self.doOutlineData, 'path': self.doPath, 'ratio': self.doRatio, 'shortcuts': self.doShortcuts, 'string': self.doString, 'strings': self.doStrings}
self.debug_count = 0 | def __init__(self, c, localFlag):
self.c = c
self.clipBoard = []
self.localFlag = localFlag
self.shortcutsDict = g.TypedDict(name='parser.shortcutsDict', keyType=type('shortcutName'), valType=g.BindingInfo)
self.openWithList = []
self.dispatchDict = {'bool': self.doBool, 'buttons': self.doButtons, 'color': self.doColor, 'commands': self.doCommands, 'data': self.doData, 'directory': self.doDirectory, 'enabledplugins': self.doEnabledPlugins, 'font': self.doFont, 'ifenv': self.doIfEnv, 'ifhostname': self.doIfHostname, 'ifplatform': self.doIfPlatform, 'ignore': self.doIgnore, 'int': self.doInt, 'ints': self.doInts, 'float': self.doFloat, 'menus': self.doMenus, 'menuat': self.doMenuat, 'popup': self.doPopup, 'mode': self.doMode, 'openwith': self.doOpenWith, 'outlinedata': self.doOutlineData, 'path': self.doPath, 'ratio': self.doRatio, 'shortcuts': self.doShortcuts, 'string': self.doString, 'strings': self.doStrings}
self.debug_count = 0<|docstring|>Ctor for the ParserBaseClass class.<|endoftext|> |
6252de63f221a788c93896bc3541a4dd3691893e63d0ab327e956e89f62ad855 | def doButtons(self, p, kind, name, val):
'Create buttons for each @button node in an @buttons tree.'
(c, tag) = (self.c, '@button')
(aList, seen) = ([], [])
after = p.nodeAfterTree()
while (p and (p != after)):
if (p.v in seen):
p.moveToNodeAfterTree()
elif p.isAtIgnoreNode():
seen.append(p.v)
p.moveToNodeAfterTree()
else:
seen.append(p.v)
if g.match_word(p.h, 0, tag):
script = g.getScript(c, p, useSelectedText=False, forcePythonSentinels=True, useSentinels=True)
command_p = p.copy()
rclicks = build_rclick_tree(command_p, top_level=True)
aList.append((command_p, script, rclicks))
p.moveToThreadNext()
if aList:
g.app.config.atCommonButtonsList.extend(aList)
g.app.config.buttonsFileName = (c.shortFileName() if c else '<no settings file>') | Create buttons for each @button node in an @buttons tree. | leo/core/leoConfig.py | doButtons | thomasbuttler/leo-editor | 1,550 | python | def doButtons(self, p, kind, name, val):
(c, tag) = (self.c, '@button')
(aList, seen) = ([], [])
after = p.nodeAfterTree()
while (p and (p != after)):
if (p.v in seen):
p.moveToNodeAfterTree()
elif p.isAtIgnoreNode():
seen.append(p.v)
p.moveToNodeAfterTree()
else:
seen.append(p.v)
if g.match_word(p.h, 0, tag):
script = g.getScript(c, p, useSelectedText=False, forcePythonSentinels=True, useSentinels=True)
command_p = p.copy()
rclicks = build_rclick_tree(command_p, top_level=True)
aList.append((command_p, script, rclicks))
p.moveToThreadNext()
if aList:
g.app.config.atCommonButtonsList.extend(aList)
g.app.config.buttonsFileName = (c.shortFileName() if c else '<no settings file>') | def doButtons(self, p, kind, name, val):
(c, tag) = (self.c, '@button')
(aList, seen) = ([], [])
after = p.nodeAfterTree()
while (p and (p != after)):
if (p.v in seen):
p.moveToNodeAfterTree()
elif p.isAtIgnoreNode():
seen.append(p.v)
p.moveToNodeAfterTree()
else:
seen.append(p.v)
if g.match_word(p.h, 0, tag):
script = g.getScript(c, p, useSelectedText=False, forcePythonSentinels=True, useSentinels=True)
command_p = p.copy()
rclicks = build_rclick_tree(command_p, top_level=True)
aList.append((command_p, script, rclicks))
p.moveToThreadNext()
if aList:
g.app.config.atCommonButtonsList.extend(aList)
g.app.config.buttonsFileName = (c.shortFileName() if c else '<no settings file>')<|docstring|>Create buttons for each @button node in an @buttons tree.<|endoftext|> |
5cd3d6587250395022f9c4a3eb02b0ccc8b758fe6e74fc8478eb625498459c8c | def doCommands(self, p, kind, name, val):
'Handle an @commands tree.'
c = self.c
aList = []
tag = '@command'
seen = []
after = p.nodeAfterTree()
while (p and (p != after)):
if (p.v in seen):
p.moveToNodeAfterTree()
elif p.isAtIgnoreNode():
seen.append(p.v)
p.moveToNodeAfterTree()
else:
seen.append(p.v)
if g.match_word(p.h, 0, tag):
script = g.getScript(c, p, useSelectedText=False, forcePythonSentinels=True, useSentinels=True)
aList.append((p.copy(), script))
p.moveToThreadNext()
if aList:
g.app.config.atCommonCommandsList.extend(aList) | Handle an @commands tree. | leo/core/leoConfig.py | doCommands | thomasbuttler/leo-editor | 1,550 | python | def doCommands(self, p, kind, name, val):
c = self.c
aList = []
tag = '@command'
seen = []
after = p.nodeAfterTree()
while (p and (p != after)):
if (p.v in seen):
p.moveToNodeAfterTree()
elif p.isAtIgnoreNode():
seen.append(p.v)
p.moveToNodeAfterTree()
else:
seen.append(p.v)
if g.match_word(p.h, 0, tag):
script = g.getScript(c, p, useSelectedText=False, forcePythonSentinels=True, useSentinels=True)
aList.append((p.copy(), script))
p.moveToThreadNext()
if aList:
g.app.config.atCommonCommandsList.extend(aList) | def doCommands(self, p, kind, name, val):
c = self.c
aList = []
tag = '@command'
seen = []
after = p.nodeAfterTree()
while (p and (p != after)):
if (p.v in seen):
p.moveToNodeAfterTree()
elif p.isAtIgnoreNode():
seen.append(p.v)
p.moveToNodeAfterTree()
else:
seen.append(p.v)
if g.match_word(p.h, 0, tag):
script = g.getScript(c, p, useSelectedText=False, forcePythonSentinels=True, useSentinels=True)
aList.append((p.copy(), script))
p.moveToThreadNext()
if aList:
g.app.config.atCommonCommandsList.extend(aList)<|docstring|>Handle an @commands tree.<|endoftext|> |
9b9079bd1b154e425230e91dc116f5f040edea8dfa4c4c5f3c4f026ba4ecf140 | def doFont(self, p, kind, name, val):
'Handle an @font node. Such nodes affect syntax coloring *only*.'
d = self.parseFont(p)
for key in ('family', 'size', 'slant', 'weight'):
data = d.get(key)
if (data is not None):
(name, val) = data
setKind = key
self.set(p, setKind, name, val) | Handle an @font node. Such nodes affect syntax coloring *only*. | leo/core/leoConfig.py | doFont | thomasbuttler/leo-editor | 1,550 | python | def doFont(self, p, kind, name, val):
d = self.parseFont(p)
for key in ('family', 'size', 'slant', 'weight'):
data = d.get(key)
if (data is not None):
(name, val) = data
setKind = key
self.set(p, setKind, name, val) | def doFont(self, p, kind, name, val):
d = self.parseFont(p)
for key in ('family', 'size', 'slant', 'weight'):
data = d.get(key)
if (data is not None):
(name, val) = data
setKind = key
self.set(p, setKind, name, val)<|docstring|>Handle an @font node. Such nodes affect syntax coloring *only*.<|endoftext|> |
b61fdd9c1650e7442719fbbf06e7c14db2969fc372c509d47bc8d307eba779ba | def doIfEnv(self, p, kind, name, val):
'\n Support @ifenv in @settings trees.\n\n Enable descendant settings if the value of os.getenv is in any of the names.\n '
aList = name.split(',')
if (not aList):
return 'skip'
name = aList[0]
env = os.getenv(name)
env = (env.lower().strip() if env else 'none')
for s in aList[1:]:
if (s.lower().strip() == env):
return None
return 'skip' | Support @ifenv in @settings trees.
Enable descendant settings if the value of os.getenv is in any of the names. | leo/core/leoConfig.py | doIfEnv | thomasbuttler/leo-editor | 1,550 | python | def doIfEnv(self, p, kind, name, val):
'\n Support @ifenv in @settings trees.\n\n Enable descendant settings if the value of os.getenv is in any of the names.\n '
aList = name.split(',')
if (not aList):
return 'skip'
name = aList[0]
env = os.getenv(name)
env = (env.lower().strip() if env else 'none')
for s in aList[1:]:
if (s.lower().strip() == env):
return None
return 'skip' | def doIfEnv(self, p, kind, name, val):
'\n Support @ifenv in @settings trees.\n\n Enable descendant settings if the value of os.getenv is in any of the names.\n '
aList = name.split(',')
if (not aList):
return 'skip'
name = aList[0]
env = os.getenv(name)
env = (env.lower().strip() if env else 'none')
for s in aList[1:]:
if (s.lower().strip() == env):
return None
return 'skip'<|docstring|>Support @ifenv in @settings trees.
Enable descendant settings if the value of os.getenv is in any of the names.<|endoftext|> |
bc0b717466a51eff3a85b05775898f460d2a2cb3662053234965b6e620ff74b7 | def doIfHostname(self, p, kind, name, val):
"\n Support @ifhostname in @settings trees.\n\n Examples: Let h = os.environ('HOSTNAME')\n\n @ifhostname bob\n Enable descendant settings if h == 'bob'\n @ifhostname !harry\n Enable descendant settings if h != 'harry'\n "
lm = g.app.loadManager
h = lm.computeMachineName().strip()
s = name.strip()
if s.startswith('!'):
if (h == s[1:]):
return 'skip'
elif (h != s):
return 'skip'
return None | Support @ifhostname in @settings trees.
Examples: Let h = os.environ('HOSTNAME')
@ifhostname bob
Enable descendant settings if h == 'bob'
@ifhostname !harry
Enable descendant settings if h != 'harry' | leo/core/leoConfig.py | doIfHostname | thomasbuttler/leo-editor | 1,550 | python | def doIfHostname(self, p, kind, name, val):
"\n Support @ifhostname in @settings trees.\n\n Examples: Let h = os.environ('HOSTNAME')\n\n @ifhostname bob\n Enable descendant settings if h == 'bob'\n @ifhostname !harry\n Enable descendant settings if h != 'harry'\n "
lm = g.app.loadManager
h = lm.computeMachineName().strip()
s = name.strip()
if s.startswith('!'):
if (h == s[1:]):
return 'skip'
elif (h != s):
return 'skip'
return None | def doIfHostname(self, p, kind, name, val):
"\n Support @ifhostname in @settings trees.\n\n Examples: Let h = os.environ('HOSTNAME')\n\n @ifhostname bob\n Enable descendant settings if h == 'bob'\n @ifhostname !harry\n Enable descendant settings if h != 'harry'\n "
lm = g.app.loadManager
h = lm.computeMachineName().strip()
s = name.strip()
if s.startswith('!'):
if (h == s[1:]):
return 'skip'
elif (h != s):
return 'skip'
return None<|docstring|>Support @ifhostname in @settings trees.
Examples: Let h = os.environ('HOSTNAME')
@ifhostname bob
Enable descendant settings if h == 'bob'
@ifhostname !harry
Enable descendant settings if h != 'harry'<|endoftext|> |
36ea40d106400a0c922063dbc25d300d8267518609aba4ab8393af967a6d96e2 | def doIfPlatform(self, p, kind, name, val):
'Support @ifplatform in @settings trees.'
platform = sys.platform.lower()
for s in name.split(','):
if (platform == s.lower()):
return None
return 'skip' | Support @ifplatform in @settings trees. | leo/core/leoConfig.py | doIfPlatform | thomasbuttler/leo-editor | 1,550 | python | def doIfPlatform(self, p, kind, name, val):
platform = sys.platform.lower()
for s in name.split(','):
if (platform == s.lower()):
return None
return 'skip' | def doIfPlatform(self, p, kind, name, val):
platform = sys.platform.lower()
for s in name.split(','):
if (platform == s.lower()):
return None
return 'skip'<|docstring|>Support @ifplatform in @settings trees.<|endoftext|> |
fdd17b37890ef1d1fb65ef5540138164f61a63375183ace29e9f2052e22c0696 | def doInts(self, p, kind, name, val):
'\n We expect either:\n @ints [val1,val2,...]aName=val\n @ints aName[val1,val2,...]=val\n '
name = name.strip()
i = name.find('[')
j = name.find(']')
if ((- 1) < i < j):
items = name[(i + 1):j]
items = items.split(',')
name = (name[:i] + name[(j + 1):].strip())
try:
items = [int(item.strip()) for item in items]
except ValueError:
items = []
self.valueError(p, 'ints[]', name, val)
return
kind = f"ints[{','.join([str(item) for item in items])}]"
try:
val = int(val)
except ValueError:
self.valueError(p, 'int', name, val)
return
if (val not in items):
self.error(f'{val} is not in {kind} in {name}')
return
self.set(p, kind, name, val) | We expect either:
@ints [val1,val2,...]aName=val
@ints aName[val1,val2,...]=val | leo/core/leoConfig.py | doInts | thomasbuttler/leo-editor | 1,550 | python | def doInts(self, p, kind, name, val):
'\n We expect either:\n @ints [val1,val2,...]aName=val\n @ints aName[val1,val2,...]=val\n '
name = name.strip()
i = name.find('[')
j = name.find(']')
if ((- 1) < i < j):
items = name[(i + 1):j]
items = items.split(',')
name = (name[:i] + name[(j + 1):].strip())
try:
items = [int(item.strip()) for item in items]
except ValueError:
items = []
self.valueError(p, 'ints[]', name, val)
return
kind = f"ints[{','.join([str(item) for item in items])}]"
try:
val = int(val)
except ValueError:
self.valueError(p, 'int', name, val)
return
if (val not in items):
self.error(f'{val} is not in {kind} in {name}')
return
self.set(p, kind, name, val) | def doInts(self, p, kind, name, val):
'\n We expect either:\n @ints [val1,val2,...]aName=val\n @ints aName[val1,val2,...]=val\n '
name = name.strip()
i = name.find('[')
j = name.find(']')
if ((- 1) < i < j):
items = name[(i + 1):j]
items = items.split(',')
name = (name[:i] + name[(j + 1):].strip())
try:
items = [int(item.strip()) for item in items]
except ValueError:
items = []
self.valueError(p, 'ints[]', name, val)
return
kind = f"ints[{','.join([str(item) for item in items])}]"
try:
val = int(val)
except ValueError:
self.valueError(p, 'int', name, val)
return
if (val not in items):
self.error(f'{val} is not in {kind} in {name}')
return
self.set(p, kind, name, val)<|docstring|>We expect either:
@ints [val1,val2,...]aName=val
@ints aName[val1,val2,...]=val<|endoftext|> |
677541c07e7b54e9a7957ba97b1f5d80411ae55d31bb252a098a6de2da7f8953 | def doMenuat(self, p, kind, name, val):
'Handle @menuat setting.'
if g.app.config.menusList:
patch: List[Any] = []
if p.hasChildren():
self.doItems(p.copy(), patch)
parts = name.split()
if (len(parts) != 3):
parts.append('subtree')
(targetPath, mode, source) = parts
if (not targetPath.startswith('/')):
targetPath = ('/' + targetPath)
ans = self.patchMenuTree(g.app.config.menusList, targetPath)
if ans:
(list_, idx) = ans
if (mode not in ('copy', 'cut')):
if (source != 'clipboard'):
use = patch
elif isinstance(self.clipBoard, list):
use = self.clipBoard
else:
use = [self.clipBoard]
if (mode == 'replace'):
list_[idx] = use.pop(0)
while use:
idx += 1
list_.insert(idx, use.pop(0))
elif (mode == 'before'):
while use:
list_.insert(idx, use.pop())
elif (mode == 'after'):
while use:
list_.insert((idx + 1), use.pop())
elif (mode == 'cut'):
self.clipBoard = list_[idx]
del list_[idx]
elif (mode == 'copy'):
self.clipBoard = list_[idx]
else:
list_.extend(use)
else:
g.es_print(("ERROR: didn't find menu path " + targetPath))
elif g.app.inBridge:
pass
else:
g.es_print('ERROR: @menuat found but no menu tree to patch') | Handle @menuat setting. | leo/core/leoConfig.py | doMenuat | thomasbuttler/leo-editor | 1,550 | python | def doMenuat(self, p, kind, name, val):
if g.app.config.menusList:
patch: List[Any] = []
if p.hasChildren():
self.doItems(p.copy(), patch)
parts = name.split()
if (len(parts) != 3):
parts.append('subtree')
(targetPath, mode, source) = parts
if (not targetPath.startswith('/')):
targetPath = ('/' + targetPath)
ans = self.patchMenuTree(g.app.config.menusList, targetPath)
if ans:
(list_, idx) = ans
if (mode not in ('copy', 'cut')):
if (source != 'clipboard'):
use = patch
elif isinstance(self.clipBoard, list):
use = self.clipBoard
else:
use = [self.clipBoard]
if (mode == 'replace'):
list_[idx] = use.pop(0)
while use:
idx += 1
list_.insert(idx, use.pop(0))
elif (mode == 'before'):
while use:
list_.insert(idx, use.pop())
elif (mode == 'after'):
while use:
list_.insert((idx + 1), use.pop())
elif (mode == 'cut'):
self.clipBoard = list_[idx]
del list_[idx]
elif (mode == 'copy'):
self.clipBoard = list_[idx]
else:
list_.extend(use)
else:
g.es_print(("ERROR: didn't find menu path " + targetPath))
elif g.app.inBridge:
pass
else:
g.es_print('ERROR: @menuat found but no menu tree to patch') | def doMenuat(self, p, kind, name, val):
if g.app.config.menusList:
patch: List[Any] = []
if p.hasChildren():
self.doItems(p.copy(), patch)
parts = name.split()
if (len(parts) != 3):
parts.append('subtree')
(targetPath, mode, source) = parts
if (not targetPath.startswith('/')):
targetPath = ('/' + targetPath)
ans = self.patchMenuTree(g.app.config.menusList, targetPath)
if ans:
(list_, idx) = ans
if (mode not in ('copy', 'cut')):
if (source != 'clipboard'):
use = patch
elif isinstance(self.clipBoard, list):
use = self.clipBoard
else:
use = [self.clipBoard]
if (mode == 'replace'):
list_[idx] = use.pop(0)
while use:
idx += 1
list_.insert(idx, use.pop(0))
elif (mode == 'before'):
while use:
list_.insert(idx, use.pop())
elif (mode == 'after'):
while use:
list_.insert((idx + 1), use.pop())
elif (mode == 'cut'):
self.clipBoard = list_[idx]
del list_[idx]
elif (mode == 'copy'):
self.clipBoard = list_[idx]
else:
list_.extend(use)
else:
g.es_print(("ERROR: didn't find menu path " + targetPath))
elif g.app.inBridge:
pass
else:
g.es_print('ERROR: @menuat found but no menu tree to patch')<|docstring|>Handle @menuat setting.<|endoftext|> |
6374edeed7395e3e9c2b3b6223aa2433aca0704f4b8144bc4fa746547dd52a7c | def doMode(self, p, kind, name, val):
'Parse an @mode node and create the enter-<name>-mode command.'
c = self.c
name1 = name
modeName = self.computeModeName(name)
d = g.TypedDict(name=f'modeDict for {modeName}', keyType=type('commandName'), valType=g.BindingInfo)
s = p.b
lines = g.splitLines(s)
for line in lines:
line = line.strip()
if (line and (not g.match(line, 0, '#'))):
(name, bi) = self.parseShortcutLine('*mode-setting*', line)
if (not name):
d.add_to_list('*entry-commands*', bi)
elif (bi is not None):
bi.pane = modeName
aList = d.get(name, [])
(key2, aList2) = c.config.getShortcut(name)
aList3 = [z for z in aList2 if (z.pane != modeName)]
if aList3:
aList.extend(aList3)
aList.append(bi)
d[name] = aList
self.createModeCommand(modeName, name1, d) | Parse an @mode node and create the enter-<name>-mode command. | leo/core/leoConfig.py | doMode | thomasbuttler/leo-editor | 1,550 | python | def doMode(self, p, kind, name, val):
c = self.c
name1 = name
modeName = self.computeModeName(name)
d = g.TypedDict(name=f'modeDict for {modeName}', keyType=type('commandName'), valType=g.BindingInfo)
s = p.b
lines = g.splitLines(s)
for line in lines:
line = line.strip()
if (line and (not g.match(line, 0, '#'))):
(name, bi) = self.parseShortcutLine('*mode-setting*', line)
if (not name):
d.add_to_list('*entry-commands*', bi)
elif (bi is not None):
bi.pane = modeName
aList = d.get(name, [])
(key2, aList2) = c.config.getShortcut(name)
aList3 = [z for z in aList2 if (z.pane != modeName)]
if aList3:
aList.extend(aList3)
aList.append(bi)
d[name] = aList
self.createModeCommand(modeName, name1, d) | def doMode(self, p, kind, name, val):
c = self.c
name1 = name
modeName = self.computeModeName(name)
d = g.TypedDict(name=f'modeDict for {modeName}', keyType=type('commandName'), valType=g.BindingInfo)
s = p.b
lines = g.splitLines(s)
for line in lines:
line = line.strip()
if (line and (not g.match(line, 0, '#'))):
(name, bi) = self.parseShortcutLine('*mode-setting*', line)
if (not name):
d.add_to_list('*entry-commands*', bi)
elif (bi is not None):
bi.pane = modeName
aList = d.get(name, [])
(key2, aList2) = c.config.getShortcut(name)
aList3 = [z for z in aList2 if (z.pane != modeName)]
if aList3:
aList.extend(aList3)
aList.append(bi)
d[name] = aList
self.createModeCommand(modeName, name1, d)<|docstring|>Parse an @mode node and create the enter-<name>-mode command.<|endoftext|> |
2f9a63b33b0d0aa4520018fca38628e5ba24b2f780ad377a836ff0873a9a02e4 | def doPopup(self, p, kind, name, val):
'\n Handle @popup menu items in @settings trees.\n '
popupName = name
aList: List[Any] = []
p = p.copy()
self.doPopupItems(p, aList)
if (not hasattr(g.app.config, 'context_menus')):
g.app.config.context_menus = {}
g.app.config.context_menus[popupName] = aList | Handle @popup menu items in @settings trees. | leo/core/leoConfig.py | doPopup | thomasbuttler/leo-editor | 1,550 | python | def doPopup(self, p, kind, name, val):
'\n \n '
popupName = name
aList: List[Any] = []
p = p.copy()
self.doPopupItems(p, aList)
if (not hasattr(g.app.config, 'context_menus')):
g.app.config.context_menus = {}
g.app.config.context_menus[popupName] = aList | def doPopup(self, p, kind, name, val):
'\n \n '
popupName = name
aList: List[Any] = []
p = p.copy()
self.doPopupItems(p, aList)
if (not hasattr(g.app.config, 'context_menus')):
g.app.config.context_menus = {}
g.app.config.context_menus[popupName] = aList<|docstring|>Handle @popup menu items in @settings trees.<|endoftext|> |
054e408847c92a310c2a716e028a3678f4e507f033811066e2abed93650e146f | def doShortcuts(self, p, kind, junk_name, junk_val, s=None):
'Handle an @shortcut or @shortcuts node.'
(c, d) = (self.c, self.shortcutsDict)
if (s is None):
s = p.b
fn = d.name()
for line in g.splitLines(s):
line = line.strip()
if (line and (not g.match(line, 0, '#'))):
(commandName, bi) = self.parseShortcutLine(fn, line)
if (bi is None):
print(f'''
Warning: bad shortcut specifier: {line!r}
''')
elif (bi and (bi.stroke not in (None, 'none', 'None'))):
self.doOneShortcut(bi, commandName, p)
elif c.config.isLocalSettingsFile():
c.k.killedBindings.append(commandName) | Handle an @shortcut or @shortcuts node. | leo/core/leoConfig.py | doShortcuts | thomasbuttler/leo-editor | 1,550 | python | def doShortcuts(self, p, kind, junk_name, junk_val, s=None):
(c, d) = (self.c, self.shortcutsDict)
if (s is None):
s = p.b
fn = d.name()
for line in g.splitLines(s):
line = line.strip()
if (line and (not g.match(line, 0, '#'))):
(commandName, bi) = self.parseShortcutLine(fn, line)
if (bi is None):
print(f'
Warning: bad shortcut specifier: {line!r}
')
elif (bi and (bi.stroke not in (None, 'none', 'None'))):
self.doOneShortcut(bi, commandName, p)
elif c.config.isLocalSettingsFile():
c.k.killedBindings.append(commandName) | def doShortcuts(self, p, kind, junk_name, junk_val, s=None):
(c, d) = (self.c, self.shortcutsDict)
if (s is None):
s = p.b
fn = d.name()
for line in g.splitLines(s):
line = line.strip()
if (line and (not g.match(line, 0, '#'))):
(commandName, bi) = self.parseShortcutLine(fn, line)
if (bi is None):
print(f'
Warning: bad shortcut specifier: {line!r}
')
elif (bi and (bi.stroke not in (None, 'none', 'None'))):
self.doOneShortcut(bi, commandName, p)
elif c.config.isLocalSettingsFile():
c.k.killedBindings.append(commandName)<|docstring|>Handle an @shortcut or @shortcuts node.<|endoftext|> |
e56904f5a95d165176e4acf783e4442b4dcb36f42baf420874990749aeddb365 | def doOneShortcut(self, bi, commandName, p):
'Handle a regular shortcut.'
d = self.shortcutsDict
aList = d.get(commandName, [])
aList.append(bi)
d[commandName] = aList | Handle a regular shortcut. | leo/core/leoConfig.py | doOneShortcut | thomasbuttler/leo-editor | 1,550 | python | def doOneShortcut(self, bi, commandName, p):
d = self.shortcutsDict
aList = d.get(commandName, [])
aList.append(bi)
d[commandName] = aList | def doOneShortcut(self, bi, commandName, p):
d = self.shortcutsDict
aList = d.get(commandName, [])
aList.append(bi)
d[commandName] = aList<|docstring|>Handle a regular shortcut.<|endoftext|> |
d7e71e344e7909a45ddc9efa419f185f72d534996060e7e1c089fb69ed6710a8 | def doStrings(self, p, kind, name, val):
'\n We expect one of the following:\n @strings aName[val1,val2...]=val\n @strings [val1,val2,...]aName=val\n '
name = name.strip()
i = name.find('[')
j = name.find(']')
if ((- 1) < i < j):
items = name[(i + 1):j]
items = items.split(',')
items = [item.strip() for item in items]
name = (name[:i] + name[(j + 1):].strip())
kind = f"strings[{','.join(items)}]"
self.set(p, kind, name, val) | We expect one of the following:
@strings aName[val1,val2...]=val
@strings [val1,val2,...]aName=val | leo/core/leoConfig.py | doStrings | thomasbuttler/leo-editor | 1,550 | python | def doStrings(self, p, kind, name, val):
'\n We expect one of the following:\n @strings aName[val1,val2...]=val\n @strings [val1,val2,...]aName=val\n '
name = name.strip()
i = name.find('[')
j = name.find(']')
if ((- 1) < i < j):
items = name[(i + 1):j]
items = items.split(',')
items = [item.strip() for item in items]
name = (name[:i] + name[(j + 1):].strip())
kind = f"strings[{','.join(items)}]"
self.set(p, kind, name, val) | def doStrings(self, p, kind, name, val):
'\n We expect one of the following:\n @strings aName[val1,val2...]=val\n @strings [val1,val2,...]aName=val\n '
name = name.strip()
i = name.find('[')
j = name.find(']')
if ((- 1) < i < j):
items = name[(i + 1):j]
items = items.split(',')
items = [item.strip() for item in items]
name = (name[:i] + name[(j + 1):].strip())
kind = f"strings[{','.join(items)}]"
self.set(p, kind, name, val)<|docstring|>We expect one of the following:
@strings aName[val1,val2...]=val
@strings [val1,val2,...]aName=val<|endoftext|> |
bdb1633f2cdc18e1219b624bcbc882269d089d677b1625b5eae22c933d150e5e | def parseHeadline(self, s):
'\n Parse a headline of the form @kind:name=val\n Return (kind,name,val).\n Leo 4.11.1: Ignore everything after @data name.\n '
kind = name = val = None
if g.match(s, 0, '@'):
i = g.skip_id(s, 1, chars='-')
i = g.skip_ws(s, i)
kind = s[1:i].strip()
if kind:
if (kind == 'data'):
j = s.find(' ', i)
if (j == (- 1)):
name = s[i:].strip()
else:
name = s[i:j].strip()
else:
j = s.find('=', i)
if (j == (- 1)):
name = s[i:].strip()
else:
name = s[i:j].strip()
val = s[(j + 1):].strip()
return (kind, name, val) | Parse a headline of the form @kind:name=val
Return (kind,name,val).
Leo 4.11.1: Ignore everything after @data name. | leo/core/leoConfig.py | parseHeadline | thomasbuttler/leo-editor | 1,550 | python | def parseHeadline(self, s):
'\n Parse a headline of the form @kind:name=val\n Return (kind,name,val).\n Leo 4.11.1: Ignore everything after @data name.\n '
kind = name = val = None
if g.match(s, 0, '@'):
i = g.skip_id(s, 1, chars='-')
i = g.skip_ws(s, i)
kind = s[1:i].strip()
if kind:
if (kind == 'data'):
j = s.find(' ', i)
if (j == (- 1)):
name = s[i:].strip()
else:
name = s[i:j].strip()
else:
j = s.find('=', i)
if (j == (- 1)):
name = s[i:].strip()
else:
name = s[i:j].strip()
val = s[(j + 1):].strip()
return (kind, name, val) | def parseHeadline(self, s):
'\n Parse a headline of the form @kind:name=val\n Return (kind,name,val).\n Leo 4.11.1: Ignore everything after @data name.\n '
kind = name = val = None
if g.match(s, 0, '@'):
i = g.skip_id(s, 1, chars='-')
i = g.skip_ws(s, i)
kind = s[1:i].strip()
if kind:
if (kind == 'data'):
j = s.find(' ', i)
if (j == (- 1)):
name = s[i:].strip()
else:
name = s[i:j].strip()
else:
j = s.find('=', i)
if (j == (- 1)):
name = s[i:].strip()
else:
name = s[i:j].strip()
val = s[(j + 1):].strip()
return (kind, name, val)<|docstring|>Parse a headline of the form @kind:name=val
Return (kind,name,val).
Leo 4.11.1: Ignore everything after @data name.<|endoftext|> |
5109b4bf231c0ca5862461c4ba20b9b9b5dbdec8474be78ef368b96247760941 | def parseShortcutLine(self, kind, s):
'Parse a shortcut line. Valid forms:\n\n --> entry-command\n settingName = shortcut\n settingName ! paneName = shortcut\n command-name --> mode-name = binding\n command-name --> same = binding\n '
s = s.replace('\x7f', '')
name = val = nextMode = None
nextMode = 'none'
i = g.skip_ws(s, 0)
if g.match(s, i, '-->'):
j = g.skip_ws(s, (i + 3))
i = g.skip_id(s, j, '-')
entryCommandName = s[j:i]
return (None, g.BindingInfo('*entry-command*', commandName=entryCommandName))
j = i
i = g.skip_id(s, j, '-@')
name = s[j:i]
for tag in ('@button-', '@command-'):
if name.startswith(tag):
name = name[len(tag):]
break
if (not name):
return (None, None)
i = g.skip_ws(s, i)
if g.match(s, i, '->'):
j = g.skip_ws(s, (i + 2))
i = g.skip_id(s, j)
nextMode = s[j:i]
i = g.skip_ws(s, i)
if g.match(s, i, '!'):
j = g.skip_ws(s, (i + 1))
i = g.skip_id(s, j)
pane = s[j:i]
if (not pane.strip()):
pane = 'all'
else:
pane = 'all'
i = g.skip_ws(s, i)
if g.match(s, i, '='):
i = g.skip_ws(s, (i + 1))
val = s[i:]
if val:
i = val.find('#')
if ((i > 0) and (val[(i - 1)] in (' ', '\t'))):
val = val[:i].strip()
if (not val):
return (name, None)
stroke = (g.KeyStroke(binding=val) if val else None)
bi = g.BindingInfo(kind=kind, nextMode=nextMode, pane=pane, stroke=stroke)
return (name, bi) | Parse a shortcut line. Valid forms:
--> entry-command
settingName = shortcut
settingName ! paneName = shortcut
command-name --> mode-name = binding
command-name --> same = binding | leo/core/leoConfig.py | parseShortcutLine | thomasbuttler/leo-editor | 1,550 | python | def parseShortcutLine(self, kind, s):
'Parse a shortcut line. Valid forms:\n\n --> entry-command\n settingName = shortcut\n settingName ! paneName = shortcut\n command-name --> mode-name = binding\n command-name --> same = binding\n '
s = s.replace('\x7f', )
name = val = nextMode = None
nextMode = 'none'
i = g.skip_ws(s, 0)
if g.match(s, i, '-->'):
j = g.skip_ws(s, (i + 3))
i = g.skip_id(s, j, '-')
entryCommandName = s[j:i]
return (None, g.BindingInfo('*entry-command*', commandName=entryCommandName))
j = i
i = g.skip_id(s, j, '-@')
name = s[j:i]
for tag in ('@button-', '@command-'):
if name.startswith(tag):
name = name[len(tag):]
break
if (not name):
return (None, None)
i = g.skip_ws(s, i)
if g.match(s, i, '->'):
j = g.skip_ws(s, (i + 2))
i = g.skip_id(s, j)
nextMode = s[j:i]
i = g.skip_ws(s, i)
if g.match(s, i, '!'):
j = g.skip_ws(s, (i + 1))
i = g.skip_id(s, j)
pane = s[j:i]
if (not pane.strip()):
pane = 'all'
else:
pane = 'all'
i = g.skip_ws(s, i)
if g.match(s, i, '='):
i = g.skip_ws(s, (i + 1))
val = s[i:]
if val:
i = val.find('#')
if ((i > 0) and (val[(i - 1)] in (' ', '\t'))):
val = val[:i].strip()
if (not val):
return (name, None)
stroke = (g.KeyStroke(binding=val) if val else None)
bi = g.BindingInfo(kind=kind, nextMode=nextMode, pane=pane, stroke=stroke)
return (name, bi) | def parseShortcutLine(self, kind, s):
'Parse a shortcut line. Valid forms:\n\n --> entry-command\n settingName = shortcut\n settingName ! paneName = shortcut\n command-name --> mode-name = binding\n command-name --> same = binding\n '
s = s.replace('\x7f', )
name = val = nextMode = None
nextMode = 'none'
i = g.skip_ws(s, 0)
if g.match(s, i, '-->'):
j = g.skip_ws(s, (i + 3))
i = g.skip_id(s, j, '-')
entryCommandName = s[j:i]
return (None, g.BindingInfo('*entry-command*', commandName=entryCommandName))
j = i
i = g.skip_id(s, j, '-@')
name = s[j:i]
for tag in ('@button-', '@command-'):
if name.startswith(tag):
name = name[len(tag):]
break
if (not name):
return (None, None)
i = g.skip_ws(s, i)
if g.match(s, i, '->'):
j = g.skip_ws(s, (i + 2))
i = g.skip_id(s, j)
nextMode = s[j:i]
i = g.skip_ws(s, i)
if g.match(s, i, '!'):
j = g.skip_ws(s, (i + 1))
i = g.skip_id(s, j)
pane = s[j:i]
if (not pane.strip()):
pane = 'all'
else:
pane = 'all'
i = g.skip_ws(s, i)
if g.match(s, i, '='):
i = g.skip_ws(s, (i + 1))
val = s[i:]
if val:
i = val.find('#')
if ((i > 0) and (val[(i - 1)] in (' ', '\t'))):
val = val[:i].strip()
if (not val):
return (name, None)
stroke = (g.KeyStroke(binding=val) if val else None)
bi = g.BindingInfo(kind=kind, nextMode=nextMode, pane=pane, stroke=stroke)
return (name, bi)<|docstring|>Parse a shortcut line. Valid forms:
--> entry-command
settingName = shortcut
settingName ! paneName = shortcut
command-name --> mode-name = binding
command-name --> same = binding<|endoftext|> |
5ed124ed610d151b2da0ce01e94f7b0f1ab88756daf6b70d3223b9c5ad45969b | def set(self, p, kind, name, val):
'Init the setting for name to val.'
c = self.c
key = self.munge(name)
if (key is None):
g.es_print('Empty setting name in', (p.h in c.fileName()))
parent = p.parent()
while parent:
g.trace('parent', parent.h)
parent.moveToParent()
return
d = self.settingsDict
gs = d.get(key)
if gs:
assert isinstance(gs, g.GeneralSetting), gs
path = gs.path
if (g.os_path_finalize(c.mFileName) != g.os_path_finalize(path)):
g.es('over-riding setting:', name, 'from', path)
d[key] = g.GeneralSetting(kind, path=c.mFileName, tag='setting', unl=(p and p.get_UNL(with_proto=True)), val=val) | Init the setting for name to val. | leo/core/leoConfig.py | set | thomasbuttler/leo-editor | 1,550 | python | def set(self, p, kind, name, val):
c = self.c
key = self.munge(name)
if (key is None):
g.es_print('Empty setting name in', (p.h in c.fileName()))
parent = p.parent()
while parent:
g.trace('parent', parent.h)
parent.moveToParent()
return
d = self.settingsDict
gs = d.get(key)
if gs:
assert isinstance(gs, g.GeneralSetting), gs
path = gs.path
if (g.os_path_finalize(c.mFileName) != g.os_path_finalize(path)):
g.es('over-riding setting:', name, 'from', path)
d[key] = g.GeneralSetting(kind, path=c.mFileName, tag='setting', unl=(p and p.get_UNL(with_proto=True)), val=val) | def set(self, p, kind, name, val):
c = self.c
key = self.munge(name)
if (key is None):
g.es_print('Empty setting name in', (p.h in c.fileName()))
parent = p.parent()
while parent:
g.trace('parent', parent.h)
parent.moveToParent()
return
d = self.settingsDict
gs = d.get(key)
if gs:
assert isinstance(gs, g.GeneralSetting), gs
path = gs.path
if (g.os_path_finalize(c.mFileName) != g.os_path_finalize(path)):
g.es('over-riding setting:', name, 'from', path)
d[key] = g.GeneralSetting(kind, path=c.mFileName, tag='setting', unl=(p and p.get_UNL(with_proto=True)), val=val)<|docstring|>Init the setting for name to val.<|endoftext|> |
4d84b261856817a5cf93442cf0688a636d46563e2e9a19dd195082d6b71354f3 | def traverse(self):
'Traverse the entire settings tree.'
c = self.c
self.settingsDict = g.TypedDict(name=f'settingsDict for {c.shortFileName()}', keyType=type('settingName'), valType=g.GeneralSetting)
self.shortcutsDict = g.TypedDict(name=f'shortcutsDict for {c.shortFileName()}', keyType=str, valType=g.BindingInfo)
p = c.config.settingsRoot()
if (not p):
return (self.shortcutsDict, self.settingsDict)
after = p.nodeAfterTree()
while (p and (p != after)):
result = self.visitNode(p)
if (result == 'skip'):
p.moveToNodeAfterTree()
else:
p.moveToThreadNext()
return (self.shortcutsDict, self.settingsDict) | Traverse the entire settings tree. | leo/core/leoConfig.py | traverse | thomasbuttler/leo-editor | 1,550 | python | def traverse(self):
c = self.c
self.settingsDict = g.TypedDict(name=f'settingsDict for {c.shortFileName()}', keyType=type('settingName'), valType=g.GeneralSetting)
self.shortcutsDict = g.TypedDict(name=f'shortcutsDict for {c.shortFileName()}', keyType=str, valType=g.BindingInfo)
p = c.config.settingsRoot()
if (not p):
return (self.shortcutsDict, self.settingsDict)
after = p.nodeAfterTree()
while (p and (p != after)):
result = self.visitNode(p)
if (result == 'skip'):
p.moveToNodeAfterTree()
else:
p.moveToThreadNext()
return (self.shortcutsDict, self.settingsDict) | def traverse(self):
c = self.c
self.settingsDict = g.TypedDict(name=f'settingsDict for {c.shortFileName()}', keyType=type('settingName'), valType=g.GeneralSetting)
self.shortcutsDict = g.TypedDict(name=f'shortcutsDict for {c.shortFileName()}', keyType=str, valType=g.BindingInfo)
p = c.config.settingsRoot()
if (not p):
return (self.shortcutsDict, self.settingsDict)
after = p.nodeAfterTree()
while (p and (p != after)):
result = self.visitNode(p)
if (result == 'skip'):
p.moveToNodeAfterTree()
else:
p.moveToThreadNext()
return (self.shortcutsDict, self.settingsDict)<|docstring|>Traverse the entire settings tree.<|endoftext|> |
da81952d7f5314735525b0d3a1d47f56f5f172b7650703ca284bd5463d476109 | def valueError(self, p, kind, name, val):
'Give an error: val is not valid for kind.'
self.error(f'{val} is not a valid {kind} for {name}') | Give an error: val is not valid for kind. | leo/core/leoConfig.py | valueError | thomasbuttler/leo-editor | 1,550 | python | def valueError(self, p, kind, name, val):
self.error(f'{val} is not a valid {kind} for {name}') | def valueError(self, p, kind, name, val):
self.error(f'{val} is not a valid {kind} for {name}')<|docstring|>Give an error: val is not valid for kind.<|endoftext|> |
96c1e04f7988eceef5610fda6ba2ea8e85298da3f2e646a4106d11904a44acd8 | def start(self):
'Do everything except populating the new outline.'
c = self.c
settings = c.config.settingsDict
shortcuts = c.config.shortcutsDict
assert isinstance(settings, g.TypedDict), repr(settings)
assert isinstance(shortcuts, g.TypedDict), repr(shortcuts)
settings_copy = settings.copy()
shortcuts_copy = shortcuts.copy()
self.commander = self.new_commander()
self.load_hidden_commanders()
self.create_commanders_list()
self.commander.config.settingsDict = settings_copy
self.commander.config.shortcutsDict = shortcuts_copy | Do everything except populating the new outline. | leo/core/leoConfig.py | start | thomasbuttler/leo-editor | 1,550 | python | def start(self):
c = self.c
settings = c.config.settingsDict
shortcuts = c.config.shortcutsDict
assert isinstance(settings, g.TypedDict), repr(settings)
assert isinstance(shortcuts, g.TypedDict), repr(shortcuts)
settings_copy = settings.copy()
shortcuts_copy = shortcuts.copy()
self.commander = self.new_commander()
self.load_hidden_commanders()
self.create_commanders_list()
self.commander.config.settingsDict = settings_copy
self.commander.config.shortcutsDict = shortcuts_copy | def start(self):
c = self.c
settings = c.config.settingsDict
shortcuts = c.config.shortcutsDict
assert isinstance(settings, g.TypedDict), repr(settings)
assert isinstance(shortcuts, g.TypedDict), repr(shortcuts)
settings_copy = settings.copy()
shortcuts_copy = shortcuts.copy()
self.commander = self.new_commander()
self.load_hidden_commanders()
self.create_commanders_list()
self.commander.config.settingsDict = settings_copy
self.commander.config.shortcutsDict = shortcuts_copy<|docstring|>Do everything except populating the new outline.<|endoftext|> |
998af1539e569b827832e7363fb61423741887878ccea888df716aad49d60967 | def create_commanders_list(self):
'Create the commanders list. Order matters.'
lm = g.app.loadManager
self.commanders = [('leoSettings', lm.leo_settings_c), ('myLeoSettings', lm.my_settings_c)]
if lm.theme_c:
self.commanders.append(('theme_file', lm.theme_c))
if self.c.config.settingsRoot():
self.commanders.append(('local_file', self.c)) | Create the commanders list. Order matters. | leo/core/leoConfig.py | create_commanders_list | thomasbuttler/leo-editor | 1,550 | python | def create_commanders_list(self):
lm = g.app.loadManager
self.commanders = [('leoSettings', lm.leo_settings_c), ('myLeoSettings', lm.my_settings_c)]
if lm.theme_c:
self.commanders.append(('theme_file', lm.theme_c))
if self.c.config.settingsRoot():
self.commanders.append(('local_file', self.c)) | def create_commanders_list(self):
lm = g.app.loadManager
self.commanders = [('leoSettings', lm.leo_settings_c), ('myLeoSettings', lm.my_settings_c)]
if lm.theme_c:
self.commanders.append(('theme_file', lm.theme_c))
if self.c.config.settingsRoot():
self.commanders.append(('local_file', self.c))<|docstring|>Create the commanders list. Order matters.<|endoftext|> |
24345f8e1f85438db10a77d5ad9e0753cbf066fe89016cfbfbe57674e6057283 | def load_hidden_commanders(self):
'\n Open hidden commanders for leoSettings.leo, myLeoSettings.leo and theme.leo.\n '
lm = g.app.loadManager
lm.readGlobalSettingsFiles()
c = g.app.commanders()[0]
fn = c.fileName()
if fn:
self.local_c = lm.openSettingsFile(fn) | Open hidden commanders for leoSettings.leo, myLeoSettings.leo and theme.leo. | leo/core/leoConfig.py | load_hidden_commanders | thomasbuttler/leo-editor | 1,550 | python | def load_hidden_commanders(self):
'\n \n '
lm = g.app.loadManager
lm.readGlobalSettingsFiles()
c = g.app.commanders()[0]
fn = c.fileName()
if fn:
self.local_c = lm.openSettingsFile(fn) | def load_hidden_commanders(self):
'\n \n '
lm = g.app.loadManager
lm.readGlobalSettingsFiles()
c = g.app.commanders()[0]
fn = c.fileName()
if fn:
self.local_c = lm.openSettingsFile(fn)<|docstring|>Open hidden commanders for leoSettings.leo, myLeoSettings.leo and theme.leo.<|endoftext|> |
61938a04f5e90ce8920e997be5fbdd790f2ebc21484c15d3027b39b40a95c516 | def new_commander(self):
'Create the new commander, and load all settings files.'
lm = g.app.loadManager
old_c = self.c
if old_c.isChanged():
old_c.save()
old_c.outerUpdate()
g.app.disable_redraw = True
g.app.setLog(None)
g.app.lockLog()
fileName = f'{old_c.fileName()}-active-settings'
g.es(fileName, color='red')
c = g.app.newCommander(fileName=fileName)
if (not old_c):
c.frame.setInitialWindowGeometry()
c.frame.resizePanesToRatio(c.frame.ratio, c.frame.secondary_ratio)
g.app.unlockLog()
lm.createMenu(c)
lm.finishOpen(c)
g.app.writeWaitingLog(c)
c.setLog()
c.clearChanged()
g.app.disable_redraw = False
return c | Create the new commander, and load all settings files. | leo/core/leoConfig.py | new_commander | thomasbuttler/leo-editor | 1,550 | python | def new_commander(self):
lm = g.app.loadManager
old_c = self.c
if old_c.isChanged():
old_c.save()
old_c.outerUpdate()
g.app.disable_redraw = True
g.app.setLog(None)
g.app.lockLog()
fileName = f'{old_c.fileName()}-active-settings'
g.es(fileName, color='red')
c = g.app.newCommander(fileName=fileName)
if (not old_c):
c.frame.setInitialWindowGeometry()
c.frame.resizePanesToRatio(c.frame.ratio, c.frame.secondary_ratio)
g.app.unlockLog()
lm.createMenu(c)
lm.finishOpen(c)
g.app.writeWaitingLog(c)
c.setLog()
c.clearChanged()
g.app.disable_redraw = False
return c | def new_commander(self):
lm = g.app.loadManager
old_c = self.c
if old_c.isChanged():
old_c.save()
old_c.outerUpdate()
g.app.disable_redraw = True
g.app.setLog(None)
g.app.lockLog()
fileName = f'{old_c.fileName()}-active-settings'
g.es(fileName, color='red')
c = g.app.newCommander(fileName=fileName)
if (not old_c):
c.frame.setInitialWindowGeometry()
c.frame.resizePanesToRatio(c.frame.ratio, c.frame.secondary_ratio)
g.app.unlockLog()
lm.createMenu(c)
lm.finishOpen(c)
g.app.writeWaitingLog(c)
c.setLog()
c.clearChanged()
g.app.disable_redraw = False
return c<|docstring|>Create the new commander, and load all settings files.<|endoftext|> |
80fd02d4fa3a08413032bce3482ff1dfd93bfb579e3aa04ae60f026e7c9f5e2e | def create_outline(self):
'Create the summary outline'
c = self.commander
root = c.rootPosition()
root.h = f'Legend for {self.c.shortFileName()}'
root.b = self.legend()
for (kind, commander) in self.commanders:
p = root.insertAfter()
p.h = g.shortFileName(commander.fileName())
p.b = '@language rest\n@wrap\n'
self.create_inner_outline(commander, kind, p)
for v in c.all_nodes():
v.clearDirty()
c.setChanged()
c.redraw() | Create the summary outline | leo/core/leoConfig.py | create_outline | thomasbuttler/leo-editor | 1,550 | python | def create_outline(self):
c = self.commander
root = c.rootPosition()
root.h = f'Legend for {self.c.shortFileName()}'
root.b = self.legend()
for (kind, commander) in self.commanders:
p = root.insertAfter()
p.h = g.shortFileName(commander.fileName())
p.b = '@language rest\n@wrap\n'
self.create_inner_outline(commander, kind, p)
for v in c.all_nodes():
v.clearDirty()
c.setChanged()
c.redraw() | def create_outline(self):
c = self.commander
root = c.rootPosition()
root.h = f'Legend for {self.c.shortFileName()}'
root.b = self.legend()
for (kind, commander) in self.commanders:
p = root.insertAfter()
p.h = g.shortFileName(commander.fileName())
p.b = '@language rest\n@wrap\n'
self.create_inner_outline(commander, kind, p)
for v in c.all_nodes():
v.clearDirty()
c.setChanged()
c.redraw()<|docstring|>Create the summary outline<|endoftext|> |
b356a09bde819dfa6bf13eb3c2573cc29a0bfa8c3fc5c44a5426002a9bf051ff | def legend(self):
'Compute legend for self.c'
(c, lm) = (self.c, g.app.loadManager)
legend = f''' @language rest
legend:
leoSettings.leo
@ @button, @command, @mode
[D] default settings
[F] local file: {c.shortFileName()}
[M] myLeoSettings.leo
'''
if lm.theme_path:
legend = (legend + f'''[T] theme file: {g.shortFileName(lm.theme_path)}
''')
return textwrap.dedent(legend) | Compute legend for self.c | leo/core/leoConfig.py | legend | thomasbuttler/leo-editor | 1,550 | python | def legend(self):
(c, lm) = (self.c, g.app.loadManager)
legend = f' @language rest
legend:
leoSettings.leo
@ @button, @command, @mode
[D] default settings
[F] local file: {c.shortFileName()}
[M] myLeoSettings.leo
'
if lm.theme_path:
legend = (legend + f'[T] theme file: {g.shortFileName(lm.theme_path)}
')
return textwrap.dedent(legend) | def legend(self):
(c, lm) = (self.c, g.app.loadManager)
legend = f' @language rest
legend:
leoSettings.leo
@ @button, @command, @mode
[D] default settings
[F] local file: {c.shortFileName()}
[M] myLeoSettings.leo
'
if lm.theme_path:
legend = (legend + f'[T] theme file: {g.shortFileName(lm.theme_path)}
')
return textwrap.dedent(legend)<|docstring|>Compute legend for self.c<|endoftext|> |
2567016839dd23e1da81828b0908d74da1cb15735d5cd0c41cd5a1ca5a5ff048 | def create_inner_outline(self, c, kind, root):
'\n Create the outline for the given hidden commander, as descendants of root.\n '
settings_root = c.config.settingsRoot()
if (not settings_root):
g.trace('no @settings node!!', c.shortFileName())
return
self.create_unified_settings(kind, root, settings_root)
self.clean(root) | Create the outline for the given hidden commander, as descendants of root. | leo/core/leoConfig.py | create_inner_outline | thomasbuttler/leo-editor | 1,550 | python | def create_inner_outline(self, c, kind, root):
'\n \n '
settings_root = c.config.settingsRoot()
if (not settings_root):
g.trace('no @settings node!!', c.shortFileName())
return
self.create_unified_settings(kind, root, settings_root)
self.clean(root) | def create_inner_outline(self, c, kind, root):
'\n \n '
settings_root = c.config.settingsRoot()
if (not settings_root):
g.trace('no @settings node!!', c.shortFileName())
return
self.create_unified_settings(kind, root, settings_root)
self.clean(root)<|docstring|>Create the outline for the given hidden commander, as descendants of root.<|endoftext|> |
91ce5bc9c108f891b765707c179e4e7aa5c9dcccfedaa328cd385a94fd2f4058 | def create_unified_settings(self, kind, root, settings_root):
'Create the active settings tree under root.'
c = self.commander
lm = g.app.loadManager
settings_pat = re.compile('^(@[\\w-]+)(\\s+[\\w\\-\\.]+)?')
valid_list = ['@bool', '@color', '@directory', '@encoding', '@int', '@float', '@ratio', '@string']
d = self.filter_settings(kind)
(ignore, outline_data) = (None, None)
self.parents = [root]
self.level = settings_root.level()
for p in settings_root.subtree():
if ignore:
if (p == ignore):
ignore = None
else:
continue
if outline_data:
if (p == outline_data):
outline_data = None
else:
self.add(p)
continue
m = settings_pat.match(p.h)
if (not m):
self.add(p, h=('ORG:' + p.h))
continue
if (m.group(2) and (m.group(1) in valid_list)):
key = g.app.config.munge(m.group(2).strip())
val = d.get(key)
if isinstance(val, g.GeneralSetting):
self.add(p)
else:
val = c.config.settingsDict.get(key)
if isinstance(val, g.GeneralSetting):
letter = lm.computeBindingLetter(self.c, val.path)
p.h = f'[{letter}] INACTIVE: {p.h}'
p.h = f'UNUSED: {p.h}'
self.add(p)
continue
if (m.group(1) == '@ignore'):
ignore = p.nodeAfterTree()
elif (m.group(1) in ('@data', '@outline-data')):
outline_data = p.nodeAfterTree()
self.add(p)
else:
self.add(p) | Create the active settings tree under root. | leo/core/leoConfig.py | create_unified_settings | thomasbuttler/leo-editor | 1,550 | python | def create_unified_settings(self, kind, root, settings_root):
c = self.commander
lm = g.app.loadManager
settings_pat = re.compile('^(@[\\w-]+)(\\s+[\\w\\-\\.]+)?')
valid_list = ['@bool', '@color', '@directory', '@encoding', '@int', '@float', '@ratio', '@string']
d = self.filter_settings(kind)
(ignore, outline_data) = (None, None)
self.parents = [root]
self.level = settings_root.level()
for p in settings_root.subtree():
if ignore:
if (p == ignore):
ignore = None
else:
continue
if outline_data:
if (p == outline_data):
outline_data = None
else:
self.add(p)
continue
m = settings_pat.match(p.h)
if (not m):
self.add(p, h=('ORG:' + p.h))
continue
if (m.group(2) and (m.group(1) in valid_list)):
key = g.app.config.munge(m.group(2).strip())
val = d.get(key)
if isinstance(val, g.GeneralSetting):
self.add(p)
else:
val = c.config.settingsDict.get(key)
if isinstance(val, g.GeneralSetting):
letter = lm.computeBindingLetter(self.c, val.path)
p.h = f'[{letter}] INACTIVE: {p.h}'
p.h = f'UNUSED: {p.h}'
self.add(p)
continue
if (m.group(1) == '@ignore'):
ignore = p.nodeAfterTree()
elif (m.group(1) in ('@data', '@outline-data')):
outline_data = p.nodeAfterTree()
self.add(p)
else:
self.add(p) | def create_unified_settings(self, kind, root, settings_root):
c = self.commander
lm = g.app.loadManager
settings_pat = re.compile('^(@[\\w-]+)(\\s+[\\w\\-\\.]+)?')
valid_list = ['@bool', '@color', '@directory', '@encoding', '@int', '@float', '@ratio', '@string']
d = self.filter_settings(kind)
(ignore, outline_data) = (None, None)
self.parents = [root]
self.level = settings_root.level()
for p in settings_root.subtree():
if ignore:
if (p == ignore):
ignore = None
else:
continue
if outline_data:
if (p == outline_data):
outline_data = None
else:
self.add(p)
continue
m = settings_pat.match(p.h)
if (not m):
self.add(p, h=('ORG:' + p.h))
continue
if (m.group(2) and (m.group(1) in valid_list)):
key = g.app.config.munge(m.group(2).strip())
val = d.get(key)
if isinstance(val, g.GeneralSetting):
self.add(p)
else:
val = c.config.settingsDict.get(key)
if isinstance(val, g.GeneralSetting):
letter = lm.computeBindingLetter(self.c, val.path)
p.h = f'[{letter}] INACTIVE: {p.h}'
p.h = f'UNUSED: {p.h}'
self.add(p)
continue
if (m.group(1) == '@ignore'):
ignore = p.nodeAfterTree()
elif (m.group(1) in ('@data', '@outline-data')):
outline_data = p.nodeAfterTree()
self.add(p)
else:
self.add(p)<|docstring|>Create the active settings tree under root.<|endoftext|> |
a140a068d772ecb5645cab38df99f4426133c07cb20570feded98ea7cb590a8d | def add(self, p, h=None):
'\n Add a node for p.\n\n We must *never* alter p in any way.\n Instead, the org flag tells whether the "ORG:" prefix.\n '
if 0:
pad = (' ' * p.level())
print(pad, p.h)
p_level = p.level()
if (p_level > (self.level + 1)):
g.trace('OOPS', p.v.context.shortFileName(), self.level, p_level, p.h)
return
while ((p_level < (self.level + 1)) and (len(self.parents) > 1)):
self.parents.pop()
self.level -= 1
parent = self.parents[(- 1)]
child = parent.insertAsLastChild()
child.h = (h or p.h)
child.b = p.b
self.parents.append(child)
self.level += 1 | Add a node for p.
We must *never* alter p in any way.
Instead, the org flag tells whether the "ORG:" prefix. | leo/core/leoConfig.py | add | thomasbuttler/leo-editor | 1,550 | python | def add(self, p, h=None):
'\n Add a node for p.\n\n We must *never* alter p in any way.\n Instead, the org flag tells whether the "ORG:" prefix.\n '
if 0:
pad = (' ' * p.level())
print(pad, p.h)
p_level = p.level()
if (p_level > (self.level + 1)):
g.trace('OOPS', p.v.context.shortFileName(), self.level, p_level, p.h)
return
while ((p_level < (self.level + 1)) and (len(self.parents) > 1)):
self.parents.pop()
self.level -= 1
parent = self.parents[(- 1)]
child = parent.insertAsLastChild()
child.h = (h or p.h)
child.b = p.b
self.parents.append(child)
self.level += 1 | def add(self, p, h=None):
'\n Add a node for p.\n\n We must *never* alter p in any way.\n Instead, the org flag tells whether the "ORG:" prefix.\n '
if 0:
pad = (' ' * p.level())
print(pad, p.h)
p_level = p.level()
if (p_level > (self.level + 1)):
g.trace('OOPS', p.v.context.shortFileName(), self.level, p_level, p.h)
return
while ((p_level < (self.level + 1)) and (len(self.parents) > 1)):
self.parents.pop()
self.level -= 1
parent = self.parents[(- 1)]
child = parent.insertAsLastChild()
child.h = (h or p.h)
child.b = p.b
self.parents.append(child)
self.level += 1<|docstring|>Add a node for p.
We must *never* alter p in any way.
Instead, the org flag tells whether the "ORG:" prefix.<|endoftext|> |
ffafecf852fd8dcb130ea5b2fae629654d18b0b33a3ebd60c575455c35f5395a | def clean(self, root):
'\n Remove all unnecessary nodes.\n Remove the "ORG:" prefix from remaining nodes.\n '
self.clean_node(root) | Remove all unnecessary nodes.
Remove the "ORG:" prefix from remaining nodes. | leo/core/leoConfig.py | clean | thomasbuttler/leo-editor | 1,550 | python | def clean(self, root):
'\n Remove all unnecessary nodes.\n Remove the "ORG:" prefix from remaining nodes.\n '
self.clean_node(root) | def clean(self, root):
'\n Remove all unnecessary nodes.\n Remove the "ORG:" prefix from remaining nodes.\n '
self.clean_node(root)<|docstring|>Remove all unnecessary nodes.
Remove the "ORG:" prefix from remaining nodes.<|endoftext|> |
aed0e8fe818e836d0c8683dc882566a9a3bbd4e6efd9f2fe9aef6b256fca11a3 | def clean_node(self, p):
'Remove p if it contains no children after cleaning its children.'
tag = 'ORG:'
for child in reversed(list(p.children())):
self.clean_node(child)
if p.h.startswith(tag):
if p.hasChildren():
p.h = p.h.lstrip(tag).strip()
else:
p.doDelete() | Remove p if it contains no children after cleaning its children. | leo/core/leoConfig.py | clean_node | thomasbuttler/leo-editor | 1,550 | python | def clean_node(self, p):
tag = 'ORG:'
for child in reversed(list(p.children())):
self.clean_node(child)
if p.h.startswith(tag):
if p.hasChildren():
p.h = p.h.lstrip(tag).strip()
else:
p.doDelete() | def clean_node(self, p):
tag = 'ORG:'
for child in reversed(list(p.children())):
self.clean_node(child)
if p.h.startswith(tag):
if p.hasChildren():
p.h = p.h.lstrip(tag).strip()
else:
p.doDelete()<|docstring|>Remove p if it contains no children after cleaning its children.<|endoftext|> |
c9925535ba965cb7d712bd4e1ebcf8725d033e5e51d378f8d330de52ae35816c | def filter_settings(self, target_kind):
'Return a dict containing only settings defined in the file given by kind.'
c = self.commander
valid_kinds = ('local_file', 'theme_file', 'myLeoSettings', 'leoSettings')
assert (target_kind in valid_kinds), repr(target_kind)
d = c.config.settingsDict
result = {}
for key in d.keys():
gs = d.get(key)
assert isinstance(gs, g.GeneralSetting), repr(gs)
if (not gs.kind):
g.trace('OOPS: no kind', repr(gs))
continue
kind = c.config.getSource(setting=gs)
if (kind == 'ignore'):
g.trace('IGNORE:', kind, key)
continue
if (kind == 'error'):
g.trace('ERROR:', kind, key)
continue
if (kind == target_kind):
result[key] = gs
return result | Return a dict containing only settings defined in the file given by kind. | leo/core/leoConfig.py | filter_settings | thomasbuttler/leo-editor | 1,550 | python | def filter_settings(self, target_kind):
c = self.commander
valid_kinds = ('local_file', 'theme_file', 'myLeoSettings', 'leoSettings')
assert (target_kind in valid_kinds), repr(target_kind)
d = c.config.settingsDict
result = {}
for key in d.keys():
gs = d.get(key)
assert isinstance(gs, g.GeneralSetting), repr(gs)
if (not gs.kind):
g.trace('OOPS: no kind', repr(gs))
continue
kind = c.config.getSource(setting=gs)
if (kind == 'ignore'):
g.trace('IGNORE:', kind, key)
continue
if (kind == 'error'):
g.trace('ERROR:', kind, key)
continue
if (kind == target_kind):
result[key] = gs
return result | def filter_settings(self, target_kind):
c = self.commander
valid_kinds = ('local_file', 'theme_file', 'myLeoSettings', 'leoSettings')
assert (target_kind in valid_kinds), repr(target_kind)
d = c.config.settingsDict
result = {}
for key in d.keys():
gs = d.get(key)
assert isinstance(gs, g.GeneralSetting), repr(gs)
if (not gs.kind):
g.trace('OOPS: no kind', repr(gs))
continue
kind = c.config.getSource(setting=gs)
if (kind == 'ignore'):
g.trace('IGNORE:', kind, key)
continue
if (kind == 'error'):
g.trace('ERROR:', kind, key)
continue
if (kind == target_kind):
result[key] = gs
return result<|docstring|>Return a dict containing only settings defined in the file given by kind.<|endoftext|> |
510f33dd632257f5d19d2464d9dcbf7fd3cde2df07bc598a303ab13b6c5d5668 | def initEncoding(self, key):
'Init g.app.config encoding ivars during initialization.'
gs = self.encodingIvarsDict.get(key)
setattr(self, gs.ivar, gs.encoding)
if (gs.encoding and (not g.isValidEncoding(gs.encoding))):
g.es('g.app.config: bad encoding:', f'{gs.ivar}: {gs.encoding}') | Init g.app.config encoding ivars during initialization. | leo/core/leoConfig.py | initEncoding | thomasbuttler/leo-editor | 1,550 | python | def initEncoding(self, key):
gs = self.encodingIvarsDict.get(key)
setattr(self, gs.ivar, gs.encoding)
if (gs.encoding and (not g.isValidEncoding(gs.encoding))):
g.es('g.app.config: bad encoding:', f'{gs.ivar}: {gs.encoding}') | def initEncoding(self, key):
gs = self.encodingIvarsDict.get(key)
setattr(self, gs.ivar, gs.encoding)
if (gs.encoding and (not g.isValidEncoding(gs.encoding))):
g.es('g.app.config: bad encoding:', f'{gs.ivar}: {gs.encoding}')<|docstring|>Init g.app.config encoding ivars during initialization.<|endoftext|> |
4228d1938d400f7739b8956702763a438c472f489a182780acf424eafee72c3b | def initIvar(self, key):
'\n Init g.app.config ivars during initialization.\n\n This does NOT init the corresponding commander ivars.\n\n Such initing must be done in setIvarsFromSettings.\n '
d = self.ivarsDict
gs = d.get(key)
setattr(self, gs.ivar, gs.val) | Init g.app.config ivars during initialization.
This does NOT init the corresponding commander ivars.
Such initing must be done in setIvarsFromSettings. | leo/core/leoConfig.py | initIvar | thomasbuttler/leo-editor | 1,550 | python | def initIvar(self, key):
'\n Init g.app.config ivars during initialization.\n\n This does NOT init the corresponding commander ivars.\n\n Such initing must be done in setIvarsFromSettings.\n '
d = self.ivarsDict
gs = d.get(key)
setattr(self, gs.ivar, gs.val) | def initIvar(self, key):
'\n Init g.app.config ivars during initialization.\n\n This does NOT init the corresponding commander ivars.\n\n Such initing must be done in setIvarsFromSettings.\n '
d = self.ivarsDict
gs = d.get(key)
setattr(self, gs.ivar, gs.val)<|docstring|>Init g.app.config ivars during initialization.
This does NOT init the corresponding commander ivars.
Such initing must be done in setIvarsFromSettings.<|endoftext|> |
b5990473897d5f8ea354026eda4411fec7e900255e9234bb7468ed5645cfe6b8 | def setIvarsFromSettings(self, c):
"\n Init g.app.config ivars or c's ivars from settings.\n\n - Called from c.initSettings with c = None to init g.app.config ivars.\n - Called from c.initSettings to init corresponding commmander ivars.\n "
if g.app.loadedThemes:
return
if (not self.inited):
return
d = self.ivarsDict
keys = list(d.keys())
keys.sort()
for key in keys:
gs = d.get(key)
if gs:
assert isinstance(gs, g.GeneralSetting)
ivar = gs.ivar
kind = gs.kind
if c:
val = c.config.get(key, kind)
else:
val = self.get(key, kind)
if c:
setattr(c, ivar, val)
if True:
setattr(self, ivar, val) | Init g.app.config ivars or c's ivars from settings.
- Called from c.initSettings with c = None to init g.app.config ivars.
- Called from c.initSettings to init corresponding commmander ivars. | leo/core/leoConfig.py | setIvarsFromSettings | thomasbuttler/leo-editor | 1,550 | python | def setIvarsFromSettings(self, c):
"\n Init g.app.config ivars or c's ivars from settings.\n\n - Called from c.initSettings with c = None to init g.app.config ivars.\n - Called from c.initSettings to init corresponding commmander ivars.\n "
if g.app.loadedThemes:
return
if (not self.inited):
return
d = self.ivarsDict
keys = list(d.keys())
keys.sort()
for key in keys:
gs = d.get(key)
if gs:
assert isinstance(gs, g.GeneralSetting)
ivar = gs.ivar
kind = gs.kind
if c:
val = c.config.get(key, kind)
else:
val = self.get(key, kind)
if c:
setattr(c, ivar, val)
if True:
setattr(self, ivar, val) | def setIvarsFromSettings(self, c):
"\n Init g.app.config ivars or c's ivars from settings.\n\n - Called from c.initSettings with c = None to init g.app.config ivars.\n - Called from c.initSettings to init corresponding commmander ivars.\n "
if g.app.loadedThemes:
return
if (not self.inited):
return
d = self.ivarsDict
keys = list(d.keys())
keys.sort()
for key in keys:
gs = d.get(key)
if gs:
assert isinstance(gs, g.GeneralSetting)
ivar = gs.ivar
kind = gs.kind
if c:
val = c.config.get(key, kind)
else:
val = self.get(key, kind)
if c:
setattr(c, ivar, val)
if True:
setattr(self, ivar, val)<|docstring|>Init g.app.config ivars or c's ivars from settings.
- Called from c.initSettings with c = None to init g.app.config ivars.
- Called from c.initSettings to init corresponding commmander ivars.<|endoftext|> |
910704b1f493a008ba9af8373fb3fb5c5d32e0cf1533e01c682164568da5eff7 | def exists(self, setting, kind):
'Return true if a setting of the given kind exists, even if it is None.'
lm = g.app.loadManager
d = lm.globalSettingsDict
if d:
(junk, found) = self.getValFromDict(d, setting, kind)
return found
return False | Return true if a setting of the given kind exists, even if it is None. | leo/core/leoConfig.py | exists | thomasbuttler/leo-editor | 1,550 | python | def exists(self, setting, kind):
lm = g.app.loadManager
d = lm.globalSettingsDict
if d:
(junk, found) = self.getValFromDict(d, setting, kind)
return found
return False | def exists(self, setting, kind):
lm = g.app.loadManager
d = lm.globalSettingsDict
if d:
(junk, found) = self.getValFromDict(d, setting, kind)
return found
return False<|docstring|>Return true if a setting of the given kind exists, even if it is None.<|endoftext|> |
d1b53e02c2d1028e563214dbf445476f40aa2c1ba3744aaf22552f64a0b9c3ff | def get(self, setting, kind):
'Get the setting and make sure its type matches the expected type.'
lm = g.app.loadManager
d = lm.globalSettingsDict
if d:
assert isinstance(d, g.TypedDict), repr(d)
(val, junk) = self.getValFromDict(d, setting, kind)
return val
return None | Get the setting and make sure its type matches the expected type. | leo/core/leoConfig.py | get | thomasbuttler/leo-editor | 1,550 | python | def get(self, setting, kind):
lm = g.app.loadManager
d = lm.globalSettingsDict
if d:
assert isinstance(d, g.TypedDict), repr(d)
(val, junk) = self.getValFromDict(d, setting, kind)
return val
return None | def get(self, setting, kind):
lm = g.app.loadManager
d = lm.globalSettingsDict
if d:
assert isinstance(d, g.TypedDict), repr(d)
(val, junk) = self.getValFromDict(d, setting, kind)
return val
return None<|docstring|>Get the setting and make sure its type matches the expected type.<|endoftext|> |
3f1629372304a5558e10dea76d549310aff401a277f6c2bb1ff970529709147b | def getValFromDict(self, d, setting, requestedType, warn=True):
'\n Look up the setting in d. If warn is True, warn if the requested type\n does not (loosely) match the actual type.\n returns (val,exists)\n '
tag = 'gcm.getValFromDict'
gs = d.get(self.munge(setting))
if (not gs):
return (None, False)
assert isinstance(gs, g.GeneralSetting), repr(gs)
val = gs.val
isNone = (val in ('None', 'none', ''))
if (not self.typesMatch(gs.kind, requestedType)):
if warn:
g.error(f'''{tag}: ignoring '{setting}' setting.
{tag}: '@{gs.kind}' is not '@{requestedType}'.
{tag}: there may be conflicting settings!''')
return (None, False)
if isNone:
return ('', True)
return (val, True) | Look up the setting in d. If warn is True, warn if the requested type
does not (loosely) match the actual type.
returns (val,exists) | leo/core/leoConfig.py | getValFromDict | thomasbuttler/leo-editor | 1,550 | python | def getValFromDict(self, d, setting, requestedType, warn=True):
'\n Look up the setting in d. If warn is True, warn if the requested type\n does not (loosely) match the actual type.\n returns (val,exists)\n '
tag = 'gcm.getValFromDict'
gs = d.get(self.munge(setting))
if (not gs):
return (None, False)
assert isinstance(gs, g.GeneralSetting), repr(gs)
val = gs.val
isNone = (val in ('None', 'none', ))
if (not self.typesMatch(gs.kind, requestedType)):
if warn:
g.error(f'{tag}: ignoring '{setting}' setting.
{tag}: '@{gs.kind}' is not '@{requestedType}'.
{tag}: there may be conflicting settings!')
return (None, False)
if isNone:
return (, True)
return (val, True) | def getValFromDict(self, d, setting, requestedType, warn=True):
'\n Look up the setting in d. If warn is True, warn if the requested type\n does not (loosely) match the actual type.\n returns (val,exists)\n '
tag = 'gcm.getValFromDict'
gs = d.get(self.munge(setting))
if (not gs):
return (None, False)
assert isinstance(gs, g.GeneralSetting), repr(gs)
val = gs.val
isNone = (val in ('None', 'none', ))
if (not self.typesMatch(gs.kind, requestedType)):
if warn:
g.error(f'{tag}: ignoring '{setting}' setting.
{tag}: '@{gs.kind}' is not '@{requestedType}'.
{tag}: there may be conflicting settings!')
return (None, False)
if isNone:
return (, True)
return (val, True)<|docstring|>Look up the setting in d. If warn is True, warn if the requested type
does not (loosely) match the actual type.
returns (val,exists)<|endoftext|> |
ed24f2d35146c34899eeabdd2be88070526fb08e941a97386dc0df07c5445b91 | def typesMatch(self, type1, type2):
'\n Return True if type1, the actual type, matches type2, the requeseted type.\n\n The following equivalences are allowed:\n\n - None matches anything.\n - An actual type of string or strings matches anything *except* shortcuts.\n - Shortcut matches shortcuts.\n '
shortcuts = ('shortcut', 'shortcuts')
if ((type1 in shortcuts) or (type2 in shortcuts)):
g.trace('oops: type in shortcuts')
return ((type1 is None) or (type2 is None) or (type1.startswith('string') and (type2 not in shortcuts)) or ((type1 == 'language') and (type2 == 'string')) or ((type1 == 'int') and (type2 == 'size')) or ((type1 in shortcuts) and (type2 in shortcuts)) or (type1 == type2)) | Return True if type1, the actual type, matches type2, the requeseted type.
The following equivalences are allowed:
- None matches anything.
- An actual type of string or strings matches anything *except* shortcuts.
- Shortcut matches shortcuts. | leo/core/leoConfig.py | typesMatch | thomasbuttler/leo-editor | 1,550 | python | def typesMatch(self, type1, type2):
'\n Return True if type1, the actual type, matches type2, the requeseted type.\n\n The following equivalences are allowed:\n\n - None matches anything.\n - An actual type of string or strings matches anything *except* shortcuts.\n - Shortcut matches shortcuts.\n '
shortcuts = ('shortcut', 'shortcuts')
if ((type1 in shortcuts) or (type2 in shortcuts)):
g.trace('oops: type in shortcuts')
return ((type1 is None) or (type2 is None) or (type1.startswith('string') and (type2 not in shortcuts)) or ((type1 == 'language') and (type2 == 'string')) or ((type1 == 'int') and (type2 == 'size')) or ((type1 in shortcuts) and (type2 in shortcuts)) or (type1 == type2)) | def typesMatch(self, type1, type2):
'\n Return True if type1, the actual type, matches type2, the requeseted type.\n\n The following equivalences are allowed:\n\n - None matches anything.\n - An actual type of string or strings matches anything *except* shortcuts.\n - Shortcut matches shortcuts.\n '
shortcuts = ('shortcut', 'shortcuts')
if ((type1 in shortcuts) or (type2 in shortcuts)):
g.trace('oops: type in shortcuts')
return ((type1 is None) or (type2 is None) or (type1.startswith('string') and (type2 not in shortcuts)) or ((type1 == 'language') and (type2 == 'string')) or ((type1 == 'int') and (type2 == 'size')) or ((type1 in shortcuts) and (type2 in shortcuts)) or (type1 == type2))<|docstring|>Return True if type1, the actual type, matches type2, the requeseted type.
The following equivalences are allowed:
- None matches anything.
- An actual type of string or strings matches anything *except* shortcuts.
- Shortcut matches shortcuts.<|endoftext|> |
430a6fd66551c4db3277ad8d4f7edce9a22ca4cc86b15d940dd6bf23f5cbe0c4 | def getAbbrevDict(self):
"Search all dictionaries for the setting & check it's type"
d = self.get('abbrev', 'abbrev')
return (d or {}) | Search all dictionaries for the setting & check it's type | leo/core/leoConfig.py | getAbbrevDict | thomasbuttler/leo-editor | 1,550 | python | def getAbbrevDict(self):
d = self.get('abbrev', 'abbrev')
return (d or {}) | def getAbbrevDict(self):
d = self.get('abbrev', 'abbrev')
return (d or {})<|docstring|>Search all dictionaries for the setting & check it's type<|endoftext|> |
527a72cb427d8498bb86e941a5c2c52d98edfa0440148f3553bd17201bc84b48 | def getBool(self, setting, default=None):
'Return the value of @bool setting, or the default if the setting is not found.'
val = self.get(setting, 'bool')
if (val in (True, False)):
return val
return default | Return the value of @bool setting, or the default if the setting is not found. | leo/core/leoConfig.py | getBool | thomasbuttler/leo-editor | 1,550 | python | def getBool(self, setting, default=None):
val = self.get(setting, 'bool')
if (val in (True, False)):
return val
return default | def getBool(self, setting, default=None):
val = self.get(setting, 'bool')
if (val in (True, False)):
return val
return default<|docstring|>Return the value of @bool setting, or the default if the setting is not found.<|endoftext|> |
7776ed37ea1d7d2d8af0ebf875874594c36e83f7538e0c14cab0e3e7ae954c33 | def getButtons(self):
'Return a list of tuples (x,y) for common @button nodes.'
return g.app.config.atCommonButtonsList | Return a list of tuples (x,y) for common @button nodes. | leo/core/leoConfig.py | getButtons | thomasbuttler/leo-editor | 1,550 | python | def getButtons(self):
return g.app.config.atCommonButtonsList | def getButtons(self):
return g.app.config.atCommonButtonsList<|docstring|>Return a list of tuples (x,y) for common @button nodes.<|endoftext|> |
1f3da4c6bca0d5896930628a78c15e94193d56ac6b60e16d7eecfb7adffe70fb | def getColor(self, setting):
'Return the value of @color setting.'
col = self.get(setting, 'color')
while (col and col.startswith('@')):
col = self.get(col[1:], 'color')
return col | Return the value of @color setting. | leo/core/leoConfig.py | getColor | thomasbuttler/leo-editor | 1,550 | python | def getColor(self, setting):
col = self.get(setting, 'color')
while (col and col.startswith('@')):
col = self.get(col[1:], 'color')
return col | def getColor(self, setting):
col = self.get(setting, 'color')
while (col and col.startswith('@')):
col = self.get(col[1:], 'color')
return col<|docstring|>Return the value of @color setting.<|endoftext|> |
97bb949c8854f3a07c3168c23b67a1e6ee4d8c8a0bdeee90de795346193590b6 | def getCommonAtCommands(self):
'Return the list of tuples (headline,script) for common @command nodes.'
return g.app.config.atCommonCommandsList | Return the list of tuples (headline,script) for common @command nodes. | leo/core/leoConfig.py | getCommonAtCommands | thomasbuttler/leo-editor | 1,550 | python | def getCommonAtCommands(self):
return g.app.config.atCommonCommandsList | def getCommonAtCommands(self):
return g.app.config.atCommonCommandsList<|docstring|>Return the list of tuples (headline,script) for common @command nodes.<|endoftext|> |
d741842330a861708fe85e330411cbb9486b97d8536cd29c7c6cb187a99db95f | def getData(self, setting, strip_comments=True, strip_data=True):
'Return a list of non-comment strings in the body text of @data setting.'
data = (self.get(setting, 'data') or [])
if (data and strip_comments):
data = [z for z in data if (not z.strip().startswith('#'))]
if (data and strip_data):
data = [z.strip() for z in data if z.strip()]
return data | Return a list of non-comment strings in the body text of @data setting. | leo/core/leoConfig.py | getData | thomasbuttler/leo-editor | 1,550 | python | def getData(self, setting, strip_comments=True, strip_data=True):
data = (self.get(setting, 'data') or [])
if (data and strip_comments):
data = [z for z in data if (not z.strip().startswith('#'))]
if (data and strip_data):
data = [z.strip() for z in data if z.strip()]
return data | def getData(self, setting, strip_comments=True, strip_data=True):
data = (self.get(setting, 'data') or [])
if (data and strip_comments):
data = [z for z in data if (not z.strip().startswith('#'))]
if (data and strip_data):
data = [z.strip() for z in data if z.strip()]
return data<|docstring|>Return a list of non-comment strings in the body text of @data setting.<|endoftext|> |
401b9126943eba2295d7748edf8e08bee7a423f3be425aee9664b0fc8284d5b9 | def getOutlineData(self, setting):
'Return the pastable (xml text) of the entire @outline-data tree.'
return self.get(setting, 'outlinedata') | Return the pastable (xml text) of the entire @outline-data tree. | leo/core/leoConfig.py | getOutlineData | thomasbuttler/leo-editor | 1,550 | python | def getOutlineData(self, setting):
return self.get(setting, 'outlinedata') | def getOutlineData(self, setting):
return self.get(setting, 'outlinedata')<|docstring|>Return the pastable (xml text) of the entire @outline-data tree.<|endoftext|> |
1683ddc00ad529fd1cbfaeca5a08f020873cad5990b6f8979afbdcc9917121f8 | def getDirectory(self, setting):
'Return the value of @directory setting, or None if the directory does not exist.'
theDir = self.get(setting, 'directory')
if (g.os_path_exists(theDir) and g.os_path_isdir(theDir)):
return theDir
return None | Return the value of @directory setting, or None if the directory does not exist. | leo/core/leoConfig.py | getDirectory | thomasbuttler/leo-editor | 1,550 | python | def getDirectory(self, setting):
theDir = self.get(setting, 'directory')
if (g.os_path_exists(theDir) and g.os_path_isdir(theDir)):
return theDir
return None | def getDirectory(self, setting):
theDir = self.get(setting, 'directory')
if (g.os_path_exists(theDir) and g.os_path_isdir(theDir)):
return theDir
return None<|docstring|>Return the value of @directory setting, or None if the directory does not exist.<|endoftext|> |
2ec12b6ce0de18dfe502e4bd41db157515c19447b4d427ef2cadeb3eef2114d8 | def getEnabledPlugins(self):
'Return the body text of the @enabled-plugins node.'
return g.app.config.enabledPluginsString | Return the body text of the @enabled-plugins node. | leo/core/leoConfig.py | getEnabledPlugins | thomasbuttler/leo-editor | 1,550 | python | def getEnabledPlugins(self):
return g.app.config.enabledPluginsString | def getEnabledPlugins(self):
return g.app.config.enabledPluginsString<|docstring|>Return the body text of the @enabled-plugins node.<|endoftext|> |
7fdbde231dcdc3a8abccdc2ea4598fb226833dc41cfbb6bfbeacbfdf4b3bd793 | def getFloat(self, setting):
'Return the value of @float setting.'
val = self.get(setting, 'float')
try:
val = float(val)
return val
except TypeError:
return None | Return the value of @float setting. | leo/core/leoConfig.py | getFloat | thomasbuttler/leo-editor | 1,550 | python | def getFloat(self, setting):
val = self.get(setting, 'float')
try:
val = float(val)
return val
except TypeError:
return None | def getFloat(self, setting):
val = self.get(setting, 'float')
try:
val = float(val)
return val
except TypeError:
return None<|docstring|>Return the value of @float setting.<|endoftext|> |
193e35339dae19deb1b3c74d3e4e3a5ccb7f9bdb9aa157836807e2796a5a5b33 | def getFontFromParams(self, family, size, slant, weight, defaultSize=12):
'Compute a font from font parameters.\n\n Arguments are the names of settings to be use.\n Default to size=12, slant="roman", weight="normal".\n\n Return None if there is no family setting so we can use system default fonts.'
family = self.get(family, 'family')
if (family in (None, '')):
family = self.defaultFontFamily
size = self.get(size, 'size')
if (size in (None, 0)):
size = defaultSize
slant = self.get(slant, 'slant')
if (slant in (None, '')):
slant = 'roman'
weight = self.get(weight, 'weight')
if (weight in (None, '')):
weight = 'normal'
return g.app.gui.getFontFromParams(family, size, slant, weight) | Compute a font from font parameters.
Arguments are the names of settings to be use.
Default to size=12, slant="roman", weight="normal".
Return None if there is no family setting so we can use system default fonts. | leo/core/leoConfig.py | getFontFromParams | thomasbuttler/leo-editor | 1,550 | python | def getFontFromParams(self, family, size, slant, weight, defaultSize=12):
'Compute a font from font parameters.\n\n Arguments are the names of settings to be use.\n Default to size=12, slant="roman", weight="normal".\n\n Return None if there is no family setting so we can use system default fonts.'
family = self.get(family, 'family')
if (family in (None, )):
family = self.defaultFontFamily
size = self.get(size, 'size')
if (size in (None, 0)):
size = defaultSize
slant = self.get(slant, 'slant')
if (slant in (None, )):
slant = 'roman'
weight = self.get(weight, 'weight')
if (weight in (None, )):
weight = 'normal'
return g.app.gui.getFontFromParams(family, size, slant, weight) | def getFontFromParams(self, family, size, slant, weight, defaultSize=12):
'Compute a font from font parameters.\n\n Arguments are the names of settings to be use.\n Default to size=12, slant="roman", weight="normal".\n\n Return None if there is no family setting so we can use system default fonts.'
family = self.get(family, 'family')
if (family in (None, )):
family = self.defaultFontFamily
size = self.get(size, 'size')
if (size in (None, 0)):
size = defaultSize
slant = self.get(slant, 'slant')
if (slant in (None, )):
slant = 'roman'
weight = self.get(weight, 'weight')
if (weight in (None, )):
weight = 'normal'
return g.app.gui.getFontFromParams(family, size, slant, weight)<|docstring|>Compute a font from font parameters.
Arguments are the names of settings to be use.
Default to size=12, slant="roman", weight="normal".
Return None if there is no family setting so we can use system default fonts.<|endoftext|> |
87d93d6d2f6d0bd214aa24a2472baa81fea33e9e5600764c882d71ebbfee899d | def getInt(self, setting):
'Return the value of @int setting.'
val = self.get(setting, 'int')
try:
val = int(val)
return val
except TypeError:
return None | Return the value of @int setting. | leo/core/leoConfig.py | getInt | thomasbuttler/leo-editor | 1,550 | python | def getInt(self, setting):
val = self.get(setting, 'int')
try:
val = int(val)
return val
except TypeError:
return None | def getInt(self, setting):
val = self.get(setting, 'int')
try:
val = int(val)
return val
except TypeError:
return None<|docstring|>Return the value of @int setting.<|endoftext|> |
9a38dcb711f57cd596fcff796fbe3a57ae016fd8d2b367a772261604011ba78f | def getLanguage(self, setting):
'Return the setting whose value should be a language known to Leo.'
language = self.getString(setting)
return language | Return the setting whose value should be a language known to Leo. | leo/core/leoConfig.py | getLanguage | thomasbuttler/leo-editor | 1,550 | python | def getLanguage(self, setting):
language = self.getString(setting)
return language | def getLanguage(self, setting):
language = self.getString(setting)
return language<|docstring|>Return the setting whose value should be a language known to Leo.<|endoftext|> |
8c10a38e251056733ae2227b4f7ae3feeb8bf2077f7bea4e441382c00f63503a | def getMenusList(self):
'Return the list of entries for the @menus tree.'
aList = self.get('menus', 'menus')
return (aList or g.app.config.menusList) | Return the list of entries for the @menus tree. | leo/core/leoConfig.py | getMenusList | thomasbuttler/leo-editor | 1,550 | python | def getMenusList(self):
aList = self.get('menus', 'menus')
return (aList or g.app.config.menusList) | def getMenusList(self):
aList = self.get('menus', 'menus')
return (aList or g.app.config.menusList)<|docstring|>Return the list of entries for the @menus tree.<|endoftext|> |
e7e94f9a9992c2fb0478a55a08d7bcc7d98bc210237c2634359ec7ed2b47de8f | def getOpenWith(self):
'Return a list of dictionaries corresponding to @openwith nodes.'
val = self.get('openwithtable', 'openwithtable')
return val | Return a list of dictionaries corresponding to @openwith nodes. | leo/core/leoConfig.py | getOpenWith | thomasbuttler/leo-editor | 1,550 | python | def getOpenWith(self):
val = self.get('openwithtable', 'openwithtable')
return val | def getOpenWith(self):
val = self.get('openwithtable', 'openwithtable')
return val<|docstring|>Return a list of dictionaries corresponding to @openwith nodes.<|endoftext|> |
fe4a68d89044f12c50b4248584c8e955ef2d57f7e97dc7bc92f83da0c9ca029b | def getRatio(self, setting):
'Return the value of @float setting.\n\n Warn if the value is less than 0.0 or greater than 1.0.'
val = self.get(setting, 'ratio')
try:
val = float(val)
if (0.0 <= val <= 1.0):
return val
except TypeError:
pass
return None | Return the value of @float setting.
Warn if the value is less than 0.0 or greater than 1.0. | leo/core/leoConfig.py | getRatio | thomasbuttler/leo-editor | 1,550 | python | def getRatio(self, setting):
'Return the value of @float setting.\n\n Warn if the value is less than 0.0 or greater than 1.0.'
val = self.get(setting, 'ratio')
try:
val = float(val)
if (0.0 <= val <= 1.0):
return val
except TypeError:
pass
return None | def getRatio(self, setting):
'Return the value of @float setting.\n\n Warn if the value is less than 0.0 or greater than 1.0.'
val = self.get(setting, 'ratio')
try:
val = float(val)
if (0.0 <= val <= 1.0):
return val
except TypeError:
pass
return None<|docstring|>Return the value of @float setting.
Warn if the value is less than 0.0 or greater than 1.0.<|endoftext|> |
24fba5f9f0bfce23091393859a2c6bc5284cba4c537784498b8bd18f8c6a89bc | def getRecentFiles(self):
'Return the list of recently opened files.'
return self.recentFiles | Return the list of recently opened files. | leo/core/leoConfig.py | getRecentFiles | thomasbuttler/leo-editor | 1,550 | python | def getRecentFiles(self):
return self.recentFiles | def getRecentFiles(self):
return self.recentFiles<|docstring|>Return the list of recently opened files.<|endoftext|> |
f9c474dff875aea71624f527486c7f4b868b9b806f7392d921f098933ba76f5f | def getString(self, setting):
'Return the value of @string setting.'
return self.get(setting, 'string') | Return the value of @string setting. | leo/core/leoConfig.py | getString | thomasbuttler/leo-editor | 1,550 | python | def getString(self, setting):
return self.get(setting, 'string') | def getString(self, setting):
return self.get(setting, 'string')<|docstring|>Return the value of @string setting.<|endoftext|> |
055d0ff31949669f249f918bb23f28c2d9dd7cff3e52cd0e2a3cb5dc5356f359 | def config_iter(self, c):
'Letters:\n leoSettings.leo\n D default settings\n F loaded .leo File\n M myLeoSettings.leo\n @ @button, @command, @mode.\n '
lm = g.app.loadManager
d = (c.config.settingsDict if c else lm.globalSettingsDict)
limit = c.config.getInt('print-settings-at-data-limit')
if (limit is None):
limit = 20
for key in sorted(list(d.keys())):
gs = d.get(key)
assert isinstance(gs, g.GeneralSetting), repr(gs)
if (gs and gs.kind):
letter = lm.computeBindingLetter(c, gs.path)
val = gs.val
if (gs.kind == 'data'):
aList = [((' ' * 8) + z.rstrip()) for z in val if (z.strip() and (not z.strip().startswith('#')))]
if (not aList):
val = '[]'
elif ((limit == 0) or (len(aList) < limit)):
val = (('\n [\n' + '\n'.join(aList)) + '\n ]')
else:
val = f'<{len(aList)} non-comment lines>'
elif (isinstance(val, str) and val.startswith('<?xml')):
val = '<xml>'
key2 = f'@{gs.kind:>6} {key}'
(yield (key2, val, c, letter)) | Letters:
leoSettings.leo
D default settings
F loaded .leo File
M myLeoSettings.leo
@ @button, @command, @mode. | leo/core/leoConfig.py | config_iter | thomasbuttler/leo-editor | 1,550 | python | def config_iter(self, c):
'Letters:\n leoSettings.leo\n D default settings\n F loaded .leo File\n M myLeoSettings.leo\n @ @button, @command, @mode.\n '
lm = g.app.loadManager
d = (c.config.settingsDict if c else lm.globalSettingsDict)
limit = c.config.getInt('print-settings-at-data-limit')
if (limit is None):
limit = 20
for key in sorted(list(d.keys())):
gs = d.get(key)
assert isinstance(gs, g.GeneralSetting), repr(gs)
if (gs and gs.kind):
letter = lm.computeBindingLetter(c, gs.path)
val = gs.val
if (gs.kind == 'data'):
aList = [((' ' * 8) + z.rstrip()) for z in val if (z.strip() and (not z.strip().startswith('#')))]
if (not aList):
val = '[]'
elif ((limit == 0) or (len(aList) < limit)):
val = (('\n [\n' + '\n'.join(aList)) + '\n ]')
else:
val = f'<{len(aList)} non-comment lines>'
elif (isinstance(val, str) and val.startswith('<?xml')):
val = '<xml>'
key2 = f'@{gs.kind:>6} {key}'
(yield (key2, val, c, letter)) | def config_iter(self, c):
'Letters:\n leoSettings.leo\n D default settings\n F loaded .leo File\n M myLeoSettings.leo\n @ @button, @command, @mode.\n '
lm = g.app.loadManager
d = (c.config.settingsDict if c else lm.globalSettingsDict)
limit = c.config.getInt('print-settings-at-data-limit')
if (limit is None):
limit = 20
for key in sorted(list(d.keys())):
gs = d.get(key)
assert isinstance(gs, g.GeneralSetting), repr(gs)
if (gs and gs.kind):
letter = lm.computeBindingLetter(c, gs.path)
val = gs.val
if (gs.kind == 'data'):
aList = [((' ' * 8) + z.rstrip()) for z in val if (z.strip() and (not z.strip().startswith('#')))]
if (not aList):
val = '[]'
elif ((limit == 0) or (len(aList) < limit)):
val = (('\n [\n' + '\n'.join(aList)) + '\n ]')
else:
val = f'<{len(aList)} non-comment lines>'
elif (isinstance(val, str) and val.startswith('<?xml')):
val = '<xml>'
key2 = f'@{gs.kind:>6} {key}'
(yield (key2, val, c, letter))<|docstring|>Letters:
leoSettings.leo
D default settings
F loaded .leo File
M myLeoSettings.leo
@ @button, @command, @mode.<|endoftext|> |
fa408650c009e057e16c2b8940c961f3aed75510036697042cee0a0bb69e39f3 | def valueInMyLeoSettings(self, settingName):
'Return the value of the setting, if any, in myLeoSettings.leo.'
lm = g.app.loadManager
d = lm.globalSettingsDict.d
gs = d.get(self.munge(settingName))
if gs:
path = gs.path
if (path.find('myLeoSettings.leo') > (- 1)):
return gs.val
return None | Return the value of the setting, if any, in myLeoSettings.leo. | leo/core/leoConfig.py | valueInMyLeoSettings | thomasbuttler/leo-editor | 1,550 | python | def valueInMyLeoSettings(self, settingName):
lm = g.app.loadManager
d = lm.globalSettingsDict.d
gs = d.get(self.munge(settingName))
if gs:
path = gs.path
if (path.find('myLeoSettings.leo') > (- 1)):
return gs.val
return None | def valueInMyLeoSettings(self, settingName):
lm = g.app.loadManager
d = lm.globalSettingsDict.d
gs = d.get(self.munge(settingName))
if gs:
path = gs.path
if (path.find('myLeoSettings.leo') > (- 1)):
return gs.val
return None<|docstring|>Return the value of the setting, if any, in myLeoSettings.leo.<|endoftext|> |
eaae3351decccb641840c1bc2b55e1ea7f737dd5f476c5e6ad6eb9a65959991c | def createActivesSettingsOutline(self):
'\n Create and open an outline, summarizing all presently active settings.\n\n The outline retains the organization of all active settings files.\n\n See #852: https://github.com/leo-editor/leo-editor/issues/852\n '
ActiveSettingsOutline(self.c) | Create and open an outline, summarizing all presently active settings.
The outline retains the organization of all active settings files.
See #852: https://github.com/leo-editor/leo-editor/issues/852 | leo/core/leoConfig.py | createActivesSettingsOutline | thomasbuttler/leo-editor | 1,550 | python | def createActivesSettingsOutline(self):
'\n Create and open an outline, summarizing all presently active settings.\n\n The outline retains the organization of all active settings files.\n\n See #852: https://github.com/leo-editor/leo-editor/issues/852\n '
ActiveSettingsOutline(self.c) | def createActivesSettingsOutline(self):
'\n Create and open an outline, summarizing all presently active settings.\n\n The outline retains the organization of all active settings files.\n\n See #852: https://github.com/leo-editor/leo-editor/issues/852\n '
ActiveSettingsOutline(self.c)<|docstring|>Create and open an outline, summarizing all presently active settings.
The outline retains the organization of all active settings files.
See #852: https://github.com/leo-editor/leo-editor/issues/852<|endoftext|> |
13e77b5fbf941bf9fbc671a87b9945e603c36e4f8dfe2a1c6acfb11643cef239 | def getSource(self, setting):
'\n Return a string representing the source file of the given setting,\n one of ("local_file", "theme_file", "myLeoSettings", "leoSettings", "ignore", "error")\n '
trace = False
if (not isinstance(setting, g.GeneralSetting)):
return 'error'
try:
path = setting.path
except Exception:
return 'error'
val = g.truncate(repr(setting.val), 50)
if (not path):
return 'local_file'
path = path.lower()
for tag in ('myLeoSettings.leo', 'leoSettings.leo'):
if path.endswith(tag.lower()):
if (setting.kind == 'color'):
if trace:
g.trace('FOUND:', tag.rstrip('.leo'), setting.kind, setting.ivar, val)
return tag.rstrip('.leo')
theme_path = g.app.loadManager.theme_path
if (theme_path and (g.shortFileName(theme_path.lower()) in path)):
if trace:
g.trace('FOUND:', 'theme_file', setting.kind, setting.ivar, val)
return 'theme_file'
if ((path == 'register-command') or (path.find('mode') > (- 1))):
return 'ignore'
return 'local_file' | Return a string representing the source file of the given setting,
one of ("local_file", "theme_file", "myLeoSettings", "leoSettings", "ignore", "error") | leo/core/leoConfig.py | getSource | thomasbuttler/leo-editor | 1,550 | python | def getSource(self, setting):
'\n Return a string representing the source file of the given setting,\n one of ("local_file", "theme_file", "myLeoSettings", "leoSettings", "ignore", "error")\n '
trace = False
if (not isinstance(setting, g.GeneralSetting)):
return 'error'
try:
path = setting.path
except Exception:
return 'error'
val = g.truncate(repr(setting.val), 50)
if (not path):
return 'local_file'
path = path.lower()
for tag in ('myLeoSettings.leo', 'leoSettings.leo'):
if path.endswith(tag.lower()):
if (setting.kind == 'color'):
if trace:
g.trace('FOUND:', tag.rstrip('.leo'), setting.kind, setting.ivar, val)
return tag.rstrip('.leo')
theme_path = g.app.loadManager.theme_path
if (theme_path and (g.shortFileName(theme_path.lower()) in path)):
if trace:
g.trace('FOUND:', 'theme_file', setting.kind, setting.ivar, val)
return 'theme_file'
if ((path == 'register-command') or (path.find('mode') > (- 1))):
return 'ignore'
return 'local_file' | def getSource(self, setting):
'\n Return a string representing the source file of the given setting,\n one of ("local_file", "theme_file", "myLeoSettings", "leoSettings", "ignore", "error")\n '
trace = False
if (not isinstance(setting, g.GeneralSetting)):
return 'error'
try:
path = setting.path
except Exception:
return 'error'
val = g.truncate(repr(setting.val), 50)
if (not path):
return 'local_file'
path = path.lower()
for tag in ('myLeoSettings.leo', 'leoSettings.leo'):
if path.endswith(tag.lower()):
if (setting.kind == 'color'):
if trace:
g.trace('FOUND:', tag.rstrip('.leo'), setting.kind, setting.ivar, val)
return tag.rstrip('.leo')
theme_path = g.app.loadManager.theme_path
if (theme_path and (g.shortFileName(theme_path.lower()) in path)):
if trace:
g.trace('FOUND:', 'theme_file', setting.kind, setting.ivar, val)
return 'theme_file'
if ((path == 'register-command') or (path.find('mode') > (- 1))):
return 'ignore'
return 'local_file'<|docstring|>Return a string representing the source file of the given setting,
one of ("local_file", "theme_file", "myLeoSettings", "leoSettings", "ignore", "error")<|endoftext|> |
7fbbe882a69a816cda2405a540ccdc3d766d09ae6423bd9366c59cff09f4708f | def findSettingsPosition(self, setting):
'Return the position for the setting in the @settings tree for c.'
munge = g.app.config.munge
root = self.settingsRoot()
if (not root):
return None
setting = munge(setting)
for p in root.subtree():
h = (munge(p.h) or '')
if h.startswith(setting):
return p.copy()
return None | Return the position for the setting in the @settings tree for c. | leo/core/leoConfig.py | findSettingsPosition | thomasbuttler/leo-editor | 1,550 | python | def findSettingsPosition(self, setting):
munge = g.app.config.munge
root = self.settingsRoot()
if (not root):
return None
setting = munge(setting)
for p in root.subtree():
h = (munge(p.h) or )
if h.startswith(setting):
return p.copy()
return None | def findSettingsPosition(self, setting):
munge = g.app.config.munge
root = self.settingsRoot()
if (not root):
return None
setting = munge(setting)
for p in root.subtree():
h = (munge(p.h) or )
if h.startswith(setting):
return p.copy()
return None<|docstring|>Return the position for the setting in the @settings tree for c.<|endoftext|> |
92424cedd57d14f1bdc941b80001782d67fd8be726943d39a7a12e016900bb85 | def settingsRoot(self):
'Return the position of the @settings tree.'
c = self.c
for p in c.all_unique_positions():
if g.match_word(p.h.rstrip(), 0, '@settings'):
return p.copy()
return None | Return the position of the @settings tree. | leo/core/leoConfig.py | settingsRoot | thomasbuttler/leo-editor | 1,550 | python | def settingsRoot(self):
c = self.c
for p in c.all_unique_positions():
if g.match_word(p.h.rstrip(), 0, '@settings'):
return p.copy()
return None | def settingsRoot(self):
c = self.c
for p in c.all_unique_positions():
if g.match_word(p.h.rstrip(), 0, '@settings'):
return p.copy()
return None<|docstring|>Return the position of the @settings tree.<|endoftext|> |
a4d9f51b3ce159aa225b923efb0f7d4ac86ea5e3d040f77992d2a53389b3d96f | def get(self, setting, kind):
'Get the setting and make sure its type matches the expected type.'
d = self.settingsDict
if d:
assert isinstance(d, g.TypedDict), repr(d)
(val, junk) = self.getValFromDict(d, setting, kind)
return val
return None | Get the setting and make sure its type matches the expected type. | leo/core/leoConfig.py | get | thomasbuttler/leo-editor | 1,550 | python | def get(self, setting, kind):
d = self.settingsDict
if d:
assert isinstance(d, g.TypedDict), repr(d)
(val, junk) = self.getValFromDict(d, setting, kind)
return val
return None | def get(self, setting, kind):
d = self.settingsDict
if d:
assert isinstance(d, g.TypedDict), repr(d)
(val, junk) = self.getValFromDict(d, setting, kind)
return val
return None<|docstring|>Get the setting and make sure its type matches the expected type.<|endoftext|> |
c6a02231a22062980d9251e49712a3d5b53287db4ea296561c44efca206cca41 | def getValFromDict(self, d, setting, requestedType, warn=True):
'\n Look up the setting in d. If warn is True, warn if the requested type\n does not (loosely) match the actual type.\n returns (val,exists)\n '
tag = 'c.config.getValFromDict'
gs = d.get(g.app.config.munge(setting))
if (not gs):
return (None, False)
assert isinstance(gs, g.GeneralSetting), repr(gs)
val = gs.val
isNone = (val in ('None', 'none', ''))
if (not self.typesMatch(gs.kind, requestedType)):
if warn:
g.error(f'''{tag}: ignoring '{setting}' setting.
{tag}: '@{gs.kind}' is not '@{requestedType}'.
{tag}: there may be conflicting settings!''')
return (None, False)
if isNone:
return ('', True)
return (val, True) | Look up the setting in d. If warn is True, warn if the requested type
does not (loosely) match the actual type.
returns (val,exists) | leo/core/leoConfig.py | getValFromDict | thomasbuttler/leo-editor | 1,550 | python | def getValFromDict(self, d, setting, requestedType, warn=True):
'\n Look up the setting in d. If warn is True, warn if the requested type\n does not (loosely) match the actual type.\n returns (val,exists)\n '
tag = 'c.config.getValFromDict'
gs = d.get(g.app.config.munge(setting))
if (not gs):
return (None, False)
assert isinstance(gs, g.GeneralSetting), repr(gs)
val = gs.val
isNone = (val in ('None', 'none', ))
if (not self.typesMatch(gs.kind, requestedType)):
if warn:
g.error(f'{tag}: ignoring '{setting}' setting.
{tag}: '@{gs.kind}' is not '@{requestedType}'.
{tag}: there may be conflicting settings!')
return (None, False)
if isNone:
return (, True)
return (val, True) | def getValFromDict(self, d, setting, requestedType, warn=True):
'\n Look up the setting in d. If warn is True, warn if the requested type\n does not (loosely) match the actual type.\n returns (val,exists)\n '
tag = 'c.config.getValFromDict'
gs = d.get(g.app.config.munge(setting))
if (not gs):
return (None, False)
assert isinstance(gs, g.GeneralSetting), repr(gs)
val = gs.val
isNone = (val in ('None', 'none', ))
if (not self.typesMatch(gs.kind, requestedType)):
if warn:
g.error(f'{tag}: ignoring '{setting}' setting.
{tag}: '@{gs.kind}' is not '@{requestedType}'.
{tag}: there may be conflicting settings!')
return (None, False)
if isNone:
return (, True)
return (val, True)<|docstring|>Look up the setting in d. If warn is True, warn if the requested type
does not (loosely) match the actual type.
returns (val,exists)<|endoftext|> |
ed24f2d35146c34899eeabdd2be88070526fb08e941a97386dc0df07c5445b91 | def typesMatch(self, type1, type2):
'\n Return True if type1, the actual type, matches type2, the requeseted type.\n\n The following equivalences are allowed:\n\n - None matches anything.\n - An actual type of string or strings matches anything *except* shortcuts.\n - Shortcut matches shortcuts.\n '
shortcuts = ('shortcut', 'shortcuts')
if ((type1 in shortcuts) or (type2 in shortcuts)):
g.trace('oops: type in shortcuts')
return ((type1 is None) or (type2 is None) or (type1.startswith('string') and (type2 not in shortcuts)) or ((type1 == 'language') and (type2 == 'string')) or ((type1 == 'int') and (type2 == 'size')) or ((type1 in shortcuts) and (type2 in shortcuts)) or (type1 == type2)) | Return True if type1, the actual type, matches type2, the requeseted type.
The following equivalences are allowed:
- None matches anything.
- An actual type of string or strings matches anything *except* shortcuts.
- Shortcut matches shortcuts. | leo/core/leoConfig.py | typesMatch | thomasbuttler/leo-editor | 1,550 | python | def typesMatch(self, type1, type2):
'\n Return True if type1, the actual type, matches type2, the requeseted type.\n\n The following equivalences are allowed:\n\n - None matches anything.\n - An actual type of string or strings matches anything *except* shortcuts.\n - Shortcut matches shortcuts.\n '
shortcuts = ('shortcut', 'shortcuts')
if ((type1 in shortcuts) or (type2 in shortcuts)):
g.trace('oops: type in shortcuts')
return ((type1 is None) or (type2 is None) or (type1.startswith('string') and (type2 not in shortcuts)) or ((type1 == 'language') and (type2 == 'string')) or ((type1 == 'int') and (type2 == 'size')) or ((type1 in shortcuts) and (type2 in shortcuts)) or (type1 == type2)) | def typesMatch(self, type1, type2):
'\n Return True if type1, the actual type, matches type2, the requeseted type.\n\n The following equivalences are allowed:\n\n - None matches anything.\n - An actual type of string or strings matches anything *except* shortcuts.\n - Shortcut matches shortcuts.\n '
shortcuts = ('shortcut', 'shortcuts')
if ((type1 in shortcuts) or (type2 in shortcuts)):
g.trace('oops: type in shortcuts')
return ((type1 is None) or (type2 is None) or (type1.startswith('string') and (type2 not in shortcuts)) or ((type1 == 'language') and (type2 == 'string')) or ((type1 == 'int') and (type2 == 'size')) or ((type1 in shortcuts) and (type2 in shortcuts)) or (type1 == type2))<|docstring|>Return True if type1, the actual type, matches type2, the requeseted type.
The following equivalences are allowed:
- None matches anything.
- An actual type of string or strings matches anything *except* shortcuts.
- Shortcut matches shortcuts.<|endoftext|> |
430a6fd66551c4db3277ad8d4f7edce9a22ca4cc86b15d940dd6bf23f5cbe0c4 | def getAbbrevDict(self):
"Search all dictionaries for the setting & check it's type"
d = self.get('abbrev', 'abbrev')
return (d or {}) | Search all dictionaries for the setting & check it's type | leo/core/leoConfig.py | getAbbrevDict | thomasbuttler/leo-editor | 1,550 | python | def getAbbrevDict(self):
d = self.get('abbrev', 'abbrev')
return (d or {}) | def getAbbrevDict(self):
d = self.get('abbrev', 'abbrev')
return (d or {})<|docstring|>Search all dictionaries for the setting & check it's type<|endoftext|> |
527a72cb427d8498bb86e941a5c2c52d98edfa0440148f3553bd17201bc84b48 | def getBool(self, setting, default=None):
'Return the value of @bool setting, or the default if the setting is not found.'
val = self.get(setting, 'bool')
if (val in (True, False)):
return val
return default | Return the value of @bool setting, or the default if the setting is not found. | leo/core/leoConfig.py | getBool | thomasbuttler/leo-editor | 1,550 | python | def getBool(self, setting, default=None):
val = self.get(setting, 'bool')
if (val in (True, False)):
return val
return default | def getBool(self, setting, default=None):
val = self.get(setting, 'bool')
if (val in (True, False)):
return val
return default<|docstring|>Return the value of @bool setting, or the default if the setting is not found.<|endoftext|> |
1f3da4c6bca0d5896930628a78c15e94193d56ac6b60e16d7eecfb7adffe70fb | def getColor(self, setting):
'Return the value of @color setting.'
col = self.get(setting, 'color')
while (col and col.startswith('@')):
col = self.get(col[1:], 'color')
return col | Return the value of @color setting. | leo/core/leoConfig.py | getColor | thomasbuttler/leo-editor | 1,550 | python | def getColor(self, setting):
col = self.get(setting, 'color')
while (col and col.startswith('@')):
col = self.get(col[1:], 'color')
return col | def getColor(self, setting):
col = self.get(setting, 'color')
while (col and col.startswith('@')):
col = self.get(col[1:], 'color')
return col<|docstring|>Return the value of @color setting.<|endoftext|> |
84fa07affae4baec19ec1300fa667fb1574ab1c4b8be4441c63973be57966cbd | def getData(self, setting, strip_comments=True, strip_data=True):
'Return a list of non-comment strings in the body text of @data setting.'
append = (setting == 'global-abbreviations')
if append:
data0 = g.app.config.getData(setting, strip_comments=strip_comments, strip_data=strip_data)
data = self.get(setting, 'data')
if isinstance(data, str):
data = [data]
if (data and strip_comments):
data = [z for z in data if (not z.strip().startswith('#'))]
if (data and strip_data):
data = [z.strip() for z in data if z.strip()]
if (append and (data != data0)):
if data:
data.extend(data0)
else:
data = data0
return data | Return a list of non-comment strings in the body text of @data setting. | leo/core/leoConfig.py | getData | thomasbuttler/leo-editor | 1,550 | python | def getData(self, setting, strip_comments=True, strip_data=True):
append = (setting == 'global-abbreviations')
if append:
data0 = g.app.config.getData(setting, strip_comments=strip_comments, strip_data=strip_data)
data = self.get(setting, 'data')
if isinstance(data, str):
data = [data]
if (data and strip_comments):
data = [z for z in data if (not z.strip().startswith('#'))]
if (data and strip_data):
data = [z.strip() for z in data if z.strip()]
if (append and (data != data0)):
if data:
data.extend(data0)
else:
data = data0
return data | def getData(self, setting, strip_comments=True, strip_data=True):
append = (setting == 'global-abbreviations')
if append:
data0 = g.app.config.getData(setting, strip_comments=strip_comments, strip_data=strip_data)
data = self.get(setting, 'data')
if isinstance(data, str):
data = [data]
if (data and strip_comments):
data = [z for z in data if (not z.strip().startswith('#'))]
if (data and strip_data):
data = [z.strip() for z in data if z.strip()]
if (append and (data != data0)):
if data:
data.extend(data0)
else:
data = data0
return data<|docstring|>Return a list of non-comment strings in the body text of @data setting.<|endoftext|> |
019e6893437e43706691f73b7cba584fcaac6e9f933c0f5441368b729c641939 | def getOutlineData(self, setting):
'Return the pastable (xml) text of the entire @outline-data tree.'
data = self.get(setting, 'outlinedata')
if (setting == 'tree-abbreviations'):
data0 = g.app.config.getOutlineData(setting)
if (data and data0 and (data != data0)):
assert isinstance(data0, str)
assert isinstance(data, str)
data = [data0, data]
return data | Return the pastable (xml) text of the entire @outline-data tree. | leo/core/leoConfig.py | getOutlineData | thomasbuttler/leo-editor | 1,550 | python | def getOutlineData(self, setting):
data = self.get(setting, 'outlinedata')
if (setting == 'tree-abbreviations'):
data0 = g.app.config.getOutlineData(setting)
if (data and data0 and (data != data0)):
assert isinstance(data0, str)
assert isinstance(data, str)
data = [data0, data]
return data | def getOutlineData(self, setting):
data = self.get(setting, 'outlinedata')
if (setting == 'tree-abbreviations'):
data0 = g.app.config.getOutlineData(setting)
if (data and data0 and (data != data0)):
assert isinstance(data0, str)
assert isinstance(data, str)
data = [data0, data]
return data<|docstring|>Return the pastable (xml) text of the entire @outline-data tree.<|endoftext|> |
1683ddc00ad529fd1cbfaeca5a08f020873cad5990b6f8979afbdcc9917121f8 | def getDirectory(self, setting):
'Return the value of @directory setting, or None if the directory does not exist.'
theDir = self.get(setting, 'directory')
if (g.os_path_exists(theDir) and g.os_path_isdir(theDir)):
return theDir
return None | Return the value of @directory setting, or None if the directory does not exist. | leo/core/leoConfig.py | getDirectory | thomasbuttler/leo-editor | 1,550 | python | def getDirectory(self, setting):
theDir = self.get(setting, 'directory')
if (g.os_path_exists(theDir) and g.os_path_isdir(theDir)):
return theDir
return None | def getDirectory(self, setting):
theDir = self.get(setting, 'directory')
if (g.os_path_exists(theDir) and g.os_path_isdir(theDir)):
return theDir
return None<|docstring|>Return the value of @directory setting, or None if the directory does not exist.<|endoftext|> |
7fdbde231dcdc3a8abccdc2ea4598fb226833dc41cfbb6bfbeacbfdf4b3bd793 | def getFloat(self, setting):
'Return the value of @float setting.'
val = self.get(setting, 'float')
try:
val = float(val)
return val
except TypeError:
return None | Return the value of @float setting. | leo/core/leoConfig.py | getFloat | thomasbuttler/leo-editor | 1,550 | python | def getFloat(self, setting):
val = self.get(setting, 'float')
try:
val = float(val)
return val
except TypeError:
return None | def getFloat(self, setting):
val = self.get(setting, 'float')
try:
val = float(val)
return val
except TypeError:
return None<|docstring|>Return the value of @float setting.<|endoftext|> |
8624152778ca9499f7f9a1e4d845556454b848a8a6acc9e54984f79ff2b18945 | def getFontFromParams(self, family, size, slant, weight, defaultSize=12):
'\n Compute a font from font parameters. This should be used *only*\n by the syntax coloring code. Otherwise, use Leo\'s style sheets.\n\n Arguments are the names of settings to be use.\n Default to size=12, slant="roman", weight="normal".\n\n Return None if there is no family setting so we can use system default fonts.\n '
family = self.get(family, 'family')
if (family in (None, '')):
family = g.app.config.defaultFontFamily
size = self.get(size, 'size')
if (size in (None, 0)):
size = defaultSize
slant = self.get(slant, 'slant')
if (slant in (None, '')):
slant = 'roman'
weight = self.get(weight, 'weight')
if (weight in (None, '')):
weight = 'normal'
return g.app.gui.getFontFromParams(family, size, slant, weight) | Compute a font from font parameters. This should be used *only*
by the syntax coloring code. Otherwise, use Leo's style sheets.
Arguments are the names of settings to be use.
Default to size=12, slant="roman", weight="normal".
Return None if there is no family setting so we can use system default fonts. | leo/core/leoConfig.py | getFontFromParams | thomasbuttler/leo-editor | 1,550 | python | def getFontFromParams(self, family, size, slant, weight, defaultSize=12):
'\n Compute a font from font parameters. This should be used *only*\n by the syntax coloring code. Otherwise, use Leo\'s style sheets.\n\n Arguments are the names of settings to be use.\n Default to size=12, slant="roman", weight="normal".\n\n Return None if there is no family setting so we can use system default fonts.\n '
family = self.get(family, 'family')
if (family in (None, )):
family = g.app.config.defaultFontFamily
size = self.get(size, 'size')
if (size in (None, 0)):
size = defaultSize
slant = self.get(slant, 'slant')
if (slant in (None, )):
slant = 'roman'
weight = self.get(weight, 'weight')
if (weight in (None, )):
weight = 'normal'
return g.app.gui.getFontFromParams(family, size, slant, weight) | def getFontFromParams(self, family, size, slant, weight, defaultSize=12):
'\n Compute a font from font parameters. This should be used *only*\n by the syntax coloring code. Otherwise, use Leo\'s style sheets.\n\n Arguments are the names of settings to be use.\n Default to size=12, slant="roman", weight="normal".\n\n Return None if there is no family setting so we can use system default fonts.\n '
family = self.get(family, 'family')
if (family in (None, )):
family = g.app.config.defaultFontFamily
size = self.get(size, 'size')
if (size in (None, 0)):
size = defaultSize
slant = self.get(slant, 'slant')
if (slant in (None, )):
slant = 'roman'
weight = self.get(weight, 'weight')
if (weight in (None, )):
weight = 'normal'
return g.app.gui.getFontFromParams(family, size, slant, weight)<|docstring|>Compute a font from font parameters. This should be used *only*
by the syntax coloring code. Otherwise, use Leo's style sheets.
Arguments are the names of settings to be use.
Default to size=12, slant="roman", weight="normal".
Return None if there is no family setting so we can use system default fonts.<|endoftext|> |
87d93d6d2f6d0bd214aa24a2472baa81fea33e9e5600764c882d71ebbfee899d | def getInt(self, setting):
'Return the value of @int setting.'
val = self.get(setting, 'int')
try:
val = int(val)
return val
except TypeError:
return None | Return the value of @int setting. | leo/core/leoConfig.py | getInt | thomasbuttler/leo-editor | 1,550 | python | def getInt(self, setting):
val = self.get(setting, 'int')
try:
val = int(val)
return val
except TypeError:
return None | def getInt(self, setting):
val = self.get(setting, 'int')
try:
val = int(val)
return val
except TypeError:
return None<|docstring|>Return the value of @int setting.<|endoftext|> |
9a38dcb711f57cd596fcff796fbe3a57ae016fd8d2b367a772261604011ba78f | def getLanguage(self, setting):
'Return the setting whose value should be a language known to Leo.'
language = self.getString(setting)
return language | Return the setting whose value should be a language known to Leo. | leo/core/leoConfig.py | getLanguage | thomasbuttler/leo-editor | 1,550 | python | def getLanguage(self, setting):
language = self.getString(setting)
return language | def getLanguage(self, setting):
language = self.getString(setting)
return language<|docstring|>Return the setting whose value should be a language known to Leo.<|endoftext|> |
8c10a38e251056733ae2227b4f7ae3feeb8bf2077f7bea4e441382c00f63503a | def getMenusList(self):
'Return the list of entries for the @menus tree.'
aList = self.get('menus', 'menus')
return (aList or g.app.config.menusList) | Return the list of entries for the @menus tree. | leo/core/leoConfig.py | getMenusList | thomasbuttler/leo-editor | 1,550 | python | def getMenusList(self):
aList = self.get('menus', 'menus')
return (aList or g.app.config.menusList) | def getMenusList(self):
aList = self.get('menus', 'menus')
return (aList or g.app.config.menusList)<|docstring|>Return the list of entries for the @menus tree.<|endoftext|> |
e7e94f9a9992c2fb0478a55a08d7bcc7d98bc210237c2634359ec7ed2b47de8f | def getOpenWith(self):
'Return a list of dictionaries corresponding to @openwith nodes.'
val = self.get('openwithtable', 'openwithtable')
return val | Return a list of dictionaries corresponding to @openwith nodes. | leo/core/leoConfig.py | getOpenWith | thomasbuttler/leo-editor | 1,550 | python | def getOpenWith(self):
val = self.get('openwithtable', 'openwithtable')
return val | def getOpenWith(self):
val = self.get('openwithtable', 'openwithtable')
return val<|docstring|>Return a list of dictionaries corresponding to @openwith nodes.<|endoftext|> |
37f26f2d2f1fb8449682f0be19a9f7e5a46a6ad51d8284458066c817c9ff6de8 | def getRatio(self, setting):
'\n Return the value of @float setting.\n\n Warn if the value is less than 0.0 or greater than 1.0.\n '
val = self.get(setting, 'ratio')
try:
val = float(val)
if (0.0 <= val <= 1.0):
return val
except TypeError:
pass
return None | Return the value of @float setting.
Warn if the value is less than 0.0 or greater than 1.0. | leo/core/leoConfig.py | getRatio | thomasbuttler/leo-editor | 1,550 | python | def getRatio(self, setting):
'\n Return the value of @float setting.\n\n Warn if the value is less than 0.0 or greater than 1.0.\n '
val = self.get(setting, 'ratio')
try:
val = float(val)
if (0.0 <= val <= 1.0):
return val
except TypeError:
pass
return None | def getRatio(self, setting):
'\n Return the value of @float setting.\n\n Warn if the value is less than 0.0 or greater than 1.0.\n '
val = self.get(setting, 'ratio')
try:
val = float(val)
if (0.0 <= val <= 1.0):
return val
except TypeError:
pass
return None<|docstring|>Return the value of @float setting.
Warn if the value is less than 0.0 or greater than 1.0.<|endoftext|> |
8e9ed663be5d930b0858c8590d5e68158baf7288823b341bcf15ec27ed1fa058 | def getSettingSource(self, setting):
'return the name of the file responsible for setting.'
d = self.settingsDict
if d:
assert isinstance(d, g.TypedDict), repr(d)
bi = d.get(setting)
if (bi is None):
return ('unknown setting', None)
return (bi.path, bi.val)
assert (d is None)
return None | return the name of the file responsible for setting. | leo/core/leoConfig.py | getSettingSource | thomasbuttler/leo-editor | 1,550 | python | def getSettingSource(self, setting):
d = self.settingsDict
if d:
assert isinstance(d, g.TypedDict), repr(d)
bi = d.get(setting)
if (bi is None):
return ('unknown setting', None)
return (bi.path, bi.val)
assert (d is None)
return None | def getSettingSource(self, setting):
d = self.settingsDict
if d:
assert isinstance(d, g.TypedDict), repr(d)
bi = d.get(setting)
if (bi is None):
return ('unknown setting', None)
return (bi.path, bi.val)
assert (d is None)
return None<|docstring|>return the name of the file responsible for setting.<|endoftext|> |
c2617125d82431a2da2ad77408a4b6dd6fe342a580910dc1bca15593434340e3 | def getShortcut(self, commandName):
'Return rawKey,accel for shortcutName'
c = self.c
d = self.shortcutsDict
if (not c.frame.menu):
if (c not in self.no_menu_dict):
self.no_menu_dict[c] = True
g.trace(f'no menu: {c.shortFileName()}:{commandName}')
return (None, [])
if d:
assert isinstance(d, g.TypedDict), repr(d)
key = c.frame.menu.canonicalizeMenuName(commandName)
key = key.replace('&', '')
aList = d.get(commandName, [])
if aList:
aList = [z for z in aList if (z.stroke and (z.stroke.lower() != 'none'))]
return (key, aList)
return (None, []) | Return rawKey,accel for shortcutName | leo/core/leoConfig.py | getShortcut | thomasbuttler/leo-editor | 1,550 | python | def getShortcut(self, commandName):
c = self.c
d = self.shortcutsDict
if (not c.frame.menu):
if (c not in self.no_menu_dict):
self.no_menu_dict[c] = True
g.trace(f'no menu: {c.shortFileName()}:{commandName}')
return (None, [])
if d:
assert isinstance(d, g.TypedDict), repr(d)
key = c.frame.menu.canonicalizeMenuName(commandName)
key = key.replace('&', )
aList = d.get(commandName, [])
if aList:
aList = [z for z in aList if (z.stroke and (z.stroke.lower() != 'none'))]
return (key, aList)
return (None, []) | def getShortcut(self, commandName):
c = self.c
d = self.shortcutsDict
if (not c.frame.menu):
if (c not in self.no_menu_dict):
self.no_menu_dict[c] = True
g.trace(f'no menu: {c.shortFileName()}:{commandName}')
return (None, [])
if d:
assert isinstance(d, g.TypedDict), repr(d)
key = c.frame.menu.canonicalizeMenuName(commandName)
key = key.replace('&', )
aList = d.get(commandName, [])
if aList:
aList = [z for z in aList if (z.stroke and (z.stroke.lower() != 'none'))]
return (key, aList)
return (None, [])<|docstring|>Return rawKey,accel for shortcutName<|endoftext|> |
f9c474dff875aea71624f527486c7f4b868b9b806f7392d921f098933ba76f5f | def getString(self, setting):
'Return the value of @string setting.'
return self.get(setting, 'string') | Return the value of @string setting. | leo/core/leoConfig.py | getString | thomasbuttler/leo-editor | 1,550 | python | def getString(self, setting):
return self.get(setting, 'string') | def getString(self, setting):
return self.get(setting, 'string')<|docstring|>Return the value of @string setting.<|endoftext|> |
7776ed37ea1d7d2d8af0ebf875874594c36e83f7538e0c14cab0e3e7ae954c33 | def getButtons(self):
'Return a list of tuples (x,y) for common @button nodes.'
return g.app.config.atCommonButtonsList | Return a list of tuples (x,y) for common @button nodes. | leo/core/leoConfig.py | getButtons | thomasbuttler/leo-editor | 1,550 | python | def getButtons(self):
return g.app.config.atCommonButtonsList | def getButtons(self):
return g.app.config.atCommonButtonsList<|docstring|>Return a list of tuples (x,y) for common @button nodes.<|endoftext|> |
16a29f00e91251656820340f0935532ca4af24a39fd34e5a25064c6a7a637b51 | def getCommands(self):
'Return the list of tuples (headline,script) for common @command nodes.'
return g.app.config.atCommonCommandsList | Return the list of tuples (headline,script) for common @command nodes. | leo/core/leoConfig.py | getCommands | thomasbuttler/leo-editor | 1,550 | python | def getCommands(self):
return g.app.config.atCommonCommandsList | def getCommands(self):
return g.app.config.atCommonCommandsList<|docstring|>Return the list of tuples (headline,script) for common @command nodes.<|endoftext|> |
2ec12b6ce0de18dfe502e4bd41db157515c19447b4d427ef2cadeb3eef2114d8 | def getEnabledPlugins(self):
'Return the body text of the @enabled-plugins node.'
return g.app.config.enabledPluginsString | Return the body text of the @enabled-plugins node. | leo/core/leoConfig.py | getEnabledPlugins | thomasbuttler/leo-editor | 1,550 | python | def getEnabledPlugins(self):
return g.app.config.enabledPluginsString | def getEnabledPlugins(self):
return g.app.config.enabledPluginsString<|docstring|>Return the body text of the @enabled-plugins node.<|endoftext|> |
0b0b4b35374af7244e141784c99152f6244bf49c2b40211f3943401913eebe1a | def getRecentFiles(self):
'Return the list of recently opened files.'
return g.app.config.getRecentFiles() | Return the list of recently opened files. | leo/core/leoConfig.py | getRecentFiles | thomasbuttler/leo-editor | 1,550 | python | def getRecentFiles(self):
return g.app.config.getRecentFiles() | def getRecentFiles(self):
return g.app.config.getRecentFiles()<|docstring|>Return the list of recently opened files.<|endoftext|> |
0af8f7a7530f2c560011271a3699dabaf89d119b5a2f9856c68b5803779dac3d | def isLocalSetting(self, setting, kind):
'Return True if the indicated setting comes from a local .leo file.'
if ((not kind) or (kind in ('shortcut', 'shortcuts', 'openwithtable'))):
return False
key = g.app.config.munge(setting)
if (key is None):
return False
if (not self.settingsDict):
return False
gs = self.settingsDict.get(key)
if (not gs):
return False
assert isinstance(gs, g.GeneralSetting), repr(gs)
path = gs.path.lower()
for fn in ('myLeoSettings.leo', 'leoSettings.leo'):
if path.endswith(fn.lower()):
return False
return True | Return True if the indicated setting comes from a local .leo file. | leo/core/leoConfig.py | isLocalSetting | thomasbuttler/leo-editor | 1,550 | python | def isLocalSetting(self, setting, kind):
if ((not kind) or (kind in ('shortcut', 'shortcuts', 'openwithtable'))):
return False
key = g.app.config.munge(setting)
if (key is None):
return False
if (not self.settingsDict):
return False
gs = self.settingsDict.get(key)
if (not gs):
return False
assert isinstance(gs, g.GeneralSetting), repr(gs)
path = gs.path.lower()
for fn in ('myLeoSettings.leo', 'leoSettings.leo'):
if path.endswith(fn.lower()):
return False
return True | def isLocalSetting(self, setting, kind):
if ((not kind) or (kind in ('shortcut', 'shortcuts', 'openwithtable'))):
return False
key = g.app.config.munge(setting)
if (key is None):
return False
if (not self.settingsDict):
return False
gs = self.settingsDict.get(key)
if (not gs):
return False
assert isinstance(gs, g.GeneralSetting), repr(gs)
path = gs.path.lower()
for fn in ('myLeoSettings.leo', 'leoSettings.leo'):
if path.endswith(fn.lower()):
return False
return True<|docstring|>Return True if the indicated setting comes from a local .leo file.<|endoftext|> |
d83278b180016b03404d8aef7017844e01a3bd97bfe6045a2ce75eb11a076776 | def isLocalSettingsFile(self):
'Return true if c is not leoSettings.leo or myLeoSettings.leo'
c = self.c
fn = c.shortFileName().lower()
for fn2 in ('leoSettings.leo', 'myLeoSettings.leo'):
if fn.endswith(fn2.lower()):
return False
return True | Return true if c is not leoSettings.leo or myLeoSettings.leo | leo/core/leoConfig.py | isLocalSettingsFile | thomasbuttler/leo-editor | 1,550 | python | def isLocalSettingsFile(self):
c = self.c
fn = c.shortFileName().lower()
for fn2 in ('leoSettings.leo', 'myLeoSettings.leo'):
if fn.endswith(fn2.lower()):
return False
return True | def isLocalSettingsFile(self):
c = self.c
fn = c.shortFileName().lower()
for fn2 in ('leoSettings.leo', 'myLeoSettings.leo'):
if fn.endswith(fn2.lower()):
return False
return True<|docstring|>Return true if c is not leoSettings.leo or myLeoSettings.leo<|endoftext|> |
6c5d4247e239e527f72e708ceb5e6757543c8cfc70ef6c0bb355b69d8ab9ac67 | def exists(self, c, setting, kind):
'Return true if a setting of the given kind exists, even if it is None.'
d = self.settingsDict
if d:
(junk, found) = self.getValFromDict(d, setting, kind)
if found:
return True
return False | Return true if a setting of the given kind exists, even if it is None. | leo/core/leoConfig.py | exists | thomasbuttler/leo-editor | 1,550 | python | def exists(self, c, setting, kind):
d = self.settingsDict
if d:
(junk, found) = self.getValFromDict(d, setting, kind)
if found:
return True
return False | def exists(self, c, setting, kind):
d = self.settingsDict
if d:
(junk, found) = self.getValFromDict(d, setting, kind)
if found:
return True
return False<|docstring|>Return true if a setting of the given kind exists, even if it is None.<|endoftext|> |
c1d28a305e03d50b16789ec49beaad3de5831150cc77412bc3624f1fa9a6ba1c | def printSettings(self):
'Prints the value of every setting, except key bindings and commands and open-with tables.\n The following shows where the active setting came from:\n\n - leoSettings.leo,\n - @ @button, @command, @mode.\n - [D] default settings.\n - [F] indicates the file being loaded,\n - [M] myLeoSettings.leo,\n - [T] theme .leo file.\n '
legend = ' legend:\n leoSettings.leo\n @ @button, @command, @mode\n [D] default settings\n [F] loaded .leo File\n [M] myLeoSettings.leo\n [T] theme .leo file.\n '
c = self.c
legend = textwrap.dedent(legend)
result = []
for (name, val, c, letter) in g.app.config.config_iter(c):
kind = (' ' if (letter == ' ') else f'[{letter}]')
result.append(f'''{kind} {name} = {val}
''')
result.append(('\n' + legend))
if g.unitTesting:
pass
else:
g.es_print('', ''.join(result), tabName='Settings') | Prints the value of every setting, except key bindings and commands and open-with tables.
The following shows where the active setting came from:
- leoSettings.leo,
- @ @button, @command, @mode.
- [D] default settings.
- [F] indicates the file being loaded,
- [M] myLeoSettings.leo,
- [T] theme .leo file. | leo/core/leoConfig.py | printSettings | thomasbuttler/leo-editor | 1,550 | python | def printSettings(self):
'Prints the value of every setting, except key bindings and commands and open-with tables.\n The following shows where the active setting came from:\n\n - leoSettings.leo,\n - @ @button, @command, @mode.\n - [D] default settings.\n - [F] indicates the file being loaded,\n - [M] myLeoSettings.leo,\n - [T] theme .leo file.\n '
legend = ' legend:\n leoSettings.leo\n @ @button, @command, @mode\n [D] default settings\n [F] loaded .leo File\n [M] myLeoSettings.leo\n [T] theme .leo file.\n '
c = self.c
legend = textwrap.dedent(legend)
result = []
for (name, val, c, letter) in g.app.config.config_iter(c):
kind = (' ' if (letter == ' ') else f'[{letter}]')
result.append(f'{kind} {name} = {val}
')
result.append(('\n' + legend))
if g.unitTesting:
pass
else:
g.es_print(, .join(result), tabName='Settings') | def printSettings(self):
'Prints the value of every setting, except key bindings and commands and open-with tables.\n The following shows where the active setting came from:\n\n - leoSettings.leo,\n - @ @button, @command, @mode.\n - [D] default settings.\n - [F] indicates the file being loaded,\n - [M] myLeoSettings.leo,\n - [T] theme .leo file.\n '
legend = ' legend:\n leoSettings.leo\n @ @button, @command, @mode\n [D] default settings\n [F] loaded .leo File\n [M] myLeoSettings.leo\n [T] theme .leo file.\n '
c = self.c
legend = textwrap.dedent(legend)
result = []
for (name, val, c, letter) in g.app.config.config_iter(c):
kind = (' ' if (letter == ' ') else f'[{letter}]')
result.append(f'{kind} {name} = {val}
')
result.append(('\n' + legend))
if g.unitTesting:
pass
else:
g.es_print(, .join(result), tabName='Settings')<|docstring|>Prints the value of every setting, except key bindings and commands and open-with tables.
The following shows where the active setting came from:
- leoSettings.leo,
- @ @button, @command, @mode.
- [D] default settings.
- [F] indicates the file being loaded,
- [M] myLeoSettings.leo,
- [T] theme .leo file.<|endoftext|> |
daa5c6825cc3cad9982dbc51035fab2c28558db1def611a34e615e7e9ada3927 | def set(self, p, kind, name, val, warn=True):
'\n Init the setting for name to val.\n\n The "p" arg is not used.\n '
c = self.c
key = g.app.config.munge(name)
d = self.settingsDict
assert isinstance(d, g.TypedDict), repr(d)
gs = d.get(key)
if gs:
assert isinstance(gs, g.GeneralSetting), repr(gs)
path = gs.path
if (warn and (g.os_path_finalize(c.mFileName) != g.os_path_finalize(path))):
g.es('over-riding setting:', name, 'from', path)
d[key] = g.GeneralSetting(kind, path=c.mFileName, val=val, tag='setting') | Init the setting for name to val.
The "p" arg is not used. | leo/core/leoConfig.py | set | thomasbuttler/leo-editor | 1,550 | python | def set(self, p, kind, name, val, warn=True):
'\n Init the setting for name to val.\n\n The "p" arg is not used.\n '
c = self.c
key = g.app.config.munge(name)
d = self.settingsDict
assert isinstance(d, g.TypedDict), repr(d)
gs = d.get(key)
if gs:
assert isinstance(gs, g.GeneralSetting), repr(gs)
path = gs.path
if (warn and (g.os_path_finalize(c.mFileName) != g.os_path_finalize(path))):
g.es('over-riding setting:', name, 'from', path)
d[key] = g.GeneralSetting(kind, path=c.mFileName, val=val, tag='setting') | def set(self, p, kind, name, val, warn=True):
'\n Init the setting for name to val.\n\n The "p" arg is not used.\n '
c = self.c
key = g.app.config.munge(name)
d = self.settingsDict
assert isinstance(d, g.TypedDict), repr(d)
gs = d.get(key)
if gs:
assert isinstance(gs, g.GeneralSetting), repr(gs)
path = gs.path
if (warn and (g.os_path_finalize(c.mFileName) != g.os_path_finalize(path))):
g.es('over-riding setting:', name, 'from', path)
d[key] = g.GeneralSetting(kind, path=c.mFileName, val=val, tag='setting')<|docstring|>Init the setting for name to val.
The "p" arg is not used.<|endoftext|> |
478f9b487cf2f8d5b1d36a22e2b08ed616ed1ecac08243df49dc24b0fc7803ca | def settingIsActiveInPath(self, gs, target_path):
'Return True if settings file given by path actually defines the setting, gs.'
assert isinstance(gs, g.GeneralSetting), repr(gs)
return (gs.path == target_path) | Return True if settings file given by path actually defines the setting, gs. | leo/core/leoConfig.py | settingIsActiveInPath | thomasbuttler/leo-editor | 1,550 | python | def settingIsActiveInPath(self, gs, target_path):
assert isinstance(gs, g.GeneralSetting), repr(gs)
return (gs.path == target_path) | def settingIsActiveInPath(self, gs, target_path):
assert isinstance(gs, g.GeneralSetting), repr(gs)
return (gs.path == target_path)<|docstring|>Return True if settings file given by path actually defines the setting, gs.<|endoftext|> |
7ddd53c204c805aa369d43eb79faa0133d95d8d68f93a9d45aaf2aaf4d14e465 | def setUserSetting(self, setting, value):
'\n Find and set the indicated setting, either in the local file or in\n myLeoSettings.leo.\n '
c = self.c
p = self.findSettingsPosition(setting)
if (not p):
c = c.openMyLeoSettings()
if (not c):
return
p = c.config.findSettingsPosition(setting)
if (not p):
root = c.config.settingsRoot()
if (not root):
return
p = c.config.findSettingsPosition(setting)
if (not p):
p = root.insertAsLastChild()
h = setting
i = h.find('=')
if (i > (- 1)):
h = h[:i].strip()
p.h = f'{h} = {value}'
c.setChanged(redrawFlag=False)
p.setDirty()
c.redraw_later() | Find and set the indicated setting, either in the local file or in
myLeoSettings.leo. | leo/core/leoConfig.py | setUserSetting | thomasbuttler/leo-editor | 1,550 | python | def setUserSetting(self, setting, value):
'\n Find and set the indicated setting, either in the local file or in\n myLeoSettings.leo.\n '
c = self.c
p = self.findSettingsPosition(setting)
if (not p):
c = c.openMyLeoSettings()
if (not c):
return
p = c.config.findSettingsPosition(setting)
if (not p):
root = c.config.settingsRoot()
if (not root):
return
p = c.config.findSettingsPosition(setting)
if (not p):
p = root.insertAsLastChild()
h = setting
i = h.find('=')
if (i > (- 1)):
h = h[:i].strip()
p.h = f'{h} = {value}'
c.setChanged(redrawFlag=False)
p.setDirty()
c.redraw_later() | def setUserSetting(self, setting, value):
'\n Find and set the indicated setting, either in the local file or in\n myLeoSettings.leo.\n '
c = self.c
p = self.findSettingsPosition(setting)
if (not p):
c = c.openMyLeoSettings()
if (not c):
return
p = c.config.findSettingsPosition(setting)
if (not p):
root = c.config.settingsRoot()
if (not root):
return
p = c.config.findSettingsPosition(setting)
if (not p):
p = root.insertAsLastChild()
h = setting
i = h.find('=')
if (i > (- 1)):
h = h[:i].strip()
p.h = f'{h} = {value}'
c.setChanged(redrawFlag=False)
p.setDirty()
c.redraw_later()<|docstring|>Find and set the indicated setting, either in the local file or in
myLeoSettings.leo.<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.