Currently, the Go to line shortcut (CTRL+G in windows/linux) only allows to navigate to a specific line.
It would be nice to optionally allow the column number to be specified after comma, e.g.
:30,11 to go to line 30, column 11
Is there any plugin or custom script to achieve this?
Update 3
This is now part of Sublime Text 3 starting in build number 3080:
Goto Anything supports :line:col syntax in addition to :line
For example, you can use :30:11 to go to line 30, column 11.
Update 1 - outdated
I just realized you've tagged this as sublime-text-3 and I'm using 2. It may work for you, but I haven't tested in 3.
Update 2 - outdated
Added some sanity checks and some modifications to GotoRowCol.py
Created github repo sublimetext2-GotoRowCol
Forked and submitted a pull request to commit addition to package_control_channel
Edit 3: all requirements of the package_control repo have been met. this package is now available in the package repository in the application ( install -> GotoRowCol to install ).
I too would like this feature. There's probably a better way to distribute this but I haven't really invested a lot of time into it. I read through some plugin dev tutorial really quick, and used some other plugin code to patch this thing together.
Select the menu option Tools -> New Plugin
A new example template will open up. Paste this into the template:
import sublime, sublime_plugin
class PromptGotoRowColCommand(sublime_plugin.WindowCommand):
def run(self, automatic = True):
self.window.show_input_panel(
'Enter a row and a column',
'1 1',
self.gotoRowCol,
None,
None
)
pass
def gotoRowCol(self, text):
try:
(row, col) = map(str, text.split(" "))
if self.window.active_view():
self.window.active_view().run_command(
"goto_row_col",
{"row": row, "col": col}
)
except ValueError:
pass
class GotoRowColCommand(sublime_plugin.TextCommand):
def run(self, edit, row, col):
print("INFO: Input: " + str({"row": row, "col": col}))
# rows and columns are zero based, so subtract 1
# convert text to int
(row, col) = (int(row) - 1, int(col) - 1)
if row > -1 and col > -1:
# col may be greater than the row length
col = min(col, len(self.view.substr(self.view.full_line(self.view.text_point(row, 0))))-1)
print("INFO: Calculated: " + str({"row": row, "col": col})) # r1.01 (->)
self.view.sel().clear()
self.view.sel().add(sublime.Region(self.view.text_point(row, col)))
self.view.show(self.view.text_point(row, col))
else:
print("ERROR: row or col are less than zero") # r1.01 (->)
Save the file. When the "Save As" dialog opens, it should be in the the Sublime Text 2\Packages\User\ directory. Navigate up one level to and create the folder Sublime Text 2\Packages\GotoRowCol\ and save the file with the name GotoRowCol.py.
Create a new file in the same directory Sublime Text 2\Packages\GotoRowCol\GotoRowCol.sublime-commands and open GotoRowCol.sublime-commands in sublime text. Paste this into the file:
[
{
"caption": "GotoRowCol",
"command": "prompt_goto_row_col"
}
]
Save the file. This should register the GotoRowCol plugin in the sublime text system. To use it, hit ctrl + shift + p then type GotoRowCol and hit ENTER. A prompt will show up at the bottom of the sublime text window with two number prepopulated, the first one is the row you want to go to, the second one is the column. Enter the values you desire, then hit ENTER.
I know this is a complex operation, but it's what I have right now and is working for me.
Related
I created an interactive dashboard using hvPlot .interactive and Panel:
template = pn.template.FastListTemplate(
title='Central Africa - Word Frequency Analysis',
sidebar=['Frequency' , yaxis],
main=[ihvplot.panel(), ipanel.panel()],
accent_base_color="#88d8b0",
header_background="#88d8b0",
sidebar_width=450,
theme='dark',
)
template.show()
Where ivplot and ipanel are my interactive plot and table, respectively. However, I would like to put instead of the table, an interactive wordcloud which I created using ipywidgets:
list1 = ['Corbeau News','Journal de Bangui','Le Potentiel','Ndjoni Sango','RJDH','Radio
Lengo Songo','Radio Ndeke Luka']
def makingclouds(Category,frame,col,atitle):
wordcloud_bangui = WordCloud(stopwords= stopword , width=1600 , height=800 ,
background_color="black",
colormap="Set2").generate(''.join(data_file_1['Content']))
plt.figure(figsize=(20,10),facecolor='k')
plt.title(atitle, fontsize=40)#,fontweight="bold")
plt.imshow(wordcloud_bangui, interpolation="bilinear")
plt.axis("off")
plt.tight_layout(pad=0)
wordcloud = interact(makingclouds, Category=list1, df=fixed(data_file_1),
col=fixed('Content'),
atitle=fixed('Most used words media - Central Africa'),
frame=fixed(data_file_1[['Source','Content']]))
My question is how can I do it. I've tried simply to put 'wordcloud' instead of itable in the 4th line of the first piece of code but it tells me that the object does not have a function panel.
What can I do?
I have some folders containing many jpg pictures (number depends on the folder)
I would like for instance to combine every 4 pict** together with the title of the image (see pict below).
(In case there is not exactly 4 image on the last sequence, I should get the number of left picture such as 3 2 or 1)
**Ideally I could change that number to other numbers like 5 6 10 (the number I chose would depend on the context) and I could chose the number of columns (I showed 2 column in my example below)
How can i perform this on Linux command or any Linux free/open-source software?
As I did not find what I want I created my own python code to solve this (it's probably not the most perfects script of the century but it works)
"""
Prints a collage according to desired number of column and rows with title of file
Instruction
1. Put all jpg picture in same folder [tested sucessfully on 12mb per pict]
2. select desired columns in NO_COL
3. select desired rowsin in NO_ROW
4. run the script which will output the collage with <cur_date>_export.png files
"""
#import libraries
import time
import os
import imageio as iio
from matplotlib import pyplot as plt
def render_collage(pict_file_name_list):
""" create one collage """
fig = plt.figure(figsize=(40, 28)) #change if needed
cnt = 1
for cur_img_name in pict_file_name_list:
img_var = iio.imread(cur_img_name)
fig.add_subplot(NO_COL, NO_ROW, cnt)
plt.imshow(img_var)
plt.axis('off')
plt.title(cur_img_name, fontsize = 30) #change if needed
cnt = cnt + 1
cur_date = time.strftime("%Y-%m-%d--%H-%M-%s")
fig.savefig(cur_date+'_export.png')
NO_COL = 3
NO_ROW = 3
NBR_IMG_COLLAGE = NO_COL * NO_ROW
img_list_name = [elem for elem in os.listdir() if 'jpg' in elem] #keep only file having .jpg
while len(img_list_name) >= 1:
sub_list = img_list_name[:NBR_IMG_COLLAGE]
render_collage(sub_list)
del img_list_name[:NBR_IMG_COLLAGE]
I've been working on creating a YAML re-formatter based on ruamel.yaml (which you can see here).
I'm currently using version 0.17.20.
Cleaning up comments and whitespace has been difficult. I want to:
ensure there is only one space before the # for EOL comments
align full line comments with the key or item immediately following
remove duplicate blank lines so there is at most one blank line
To get closer to achieving that, I have a custom Emitter class where I extend write_comment to adjust the comments just before writing with super().write_comment(...). However, the Emitter does not know about which key or item comes next because comments are generally attached as post comments.
As I've studied the ruamel.yaml code to figure out how to do this, I found the rtsc mode (Round Trip Split Comments) which looks fantastic because it separates EOLComment, BlankLineComment and FullLineComment instead of lumping them together.
From what I can tell, the Parser and Scanner have been adjusted to capture the comments. So, loading is (mostly?) implemented with this "NEWCMNT" implementation. But Emitter.write_comment expects CommentToken instead of comment line numbers, so dumping does not work yet.
If I update my Emitter.write_comment method, is that enough to finish dumping? Or what else might be necessary? In one of my tries, I ran into a sys.exit in ScannedComments.assign_eol() - what else is needed to finish that?
PS: I wouldn't normally ask how to collaborate on StackOverflow, but this is not a bug report or a feature request, and I'm trying/failing to use a new (undocumented) feature, so I'm filing this here instead of sourceforge.
rtsc is work in progress cq work started but unfinished. It's internals will almost certainly change.
Two of the three points you indicate can relatively easy be implemented:
set the column of each comment to 0 ( by recursively going over a loaded data structure similar to here ) if the column is before the position of the end of the value on a line, you'll get one space between the value and the column
at the same time doing the recursion in the previous point. Take each comment value and do something like:
value = '\n'.join(line.strip() for line in value.splitlines()
while '\n\n\n' in value:
value = value.replace('\n\n\n', '\n\n')
The indentation to the following element is difficult, depends on the
data structure etc. Given that these are full line comments, I suggest
you do some postprocessing of the YAML document you generate:
find a full line comment, gather full line comments until next line is
not full line comment (i.e. some "real" YAML). Since full line comments
are in column[0] if the previous stuff is applied, you don't have to
track if you are in a (multi-line) literal or folded scalar string where
one of the lines happens to start with #
determine number of spaces
before real YAML and apply these to the full line comments.
import sys
import ruamel.yaml
yaml_str = """\
# the following is a example YAML doc
a:
- b: 42
# collapse multiple empty lines
c: |
# this is not a comment
it is the first line of a block style literal scalar
processing this gobbles a newline which doesn't go into a comment
# that is unless you have a (dedented) comment directly following
d: 42 # and some non-full line comment
e: # another one
# and some more comments to align
f: glitter in the dark near the Tannhäuser gate
"""
def redo_comments(d):
def do_one(comment):
if not comment:
return
comment.column = 0
value = '\n'.join(line.strip() for line in comment.value.splitlines()) + '\n'
while '\n\n\n' in value:
value = value.replace('\n\n\n', '\n\n')
comment.value = value
def do_values(v):
for x in v:
for comment in x:
do_one(comment)
def do_loc(v):
if v is None:
return
do_one(v[0])
if not v[1]:
return
for comment in v[1]:
do_one(comment)
if isinstance(d, dict):
do_loc(d.ca.comment)
do_values(d.ca.items.values())
for val in d.values():
redo_comments(val)
elif isinstance(d, list):
do_values(d.ca.items.values())
for elem in d:
redo_comments(elem)
def realign_full_line_comments(s):
res = []
buf = []
for line in s.splitlines(True):
if not buf:
if line and line[0] == '#':
buf.append(line)
else:
res.append(line)
else:
if line[0] in '#\n':
buf.append(line)
else:
# YAML line, determine indent
count = 0
while line[count] == ' ':
count += 1
if count > len(line):
break # superfluous?
indent = ' ' * count
for cline in buf:
if cline[0] == '\n': # empty
res.append(cline)
else:
res.append(indent + cline)
buf = []
res.append(line)
return ''.join(res)
yaml = ruamel.yaml.YAML()
# yaml.indent(mapping=4, sequence=4, offset=2)
# yaml.preserve_quotes = True
data = yaml.load(yaml_str)
redo_comments(data)
yaml.dump(data, sys.stdout, transform=realign_full_line_comments)
which gives:
# the following is a example YAML doc
a:
- b: 42
# collapse multiple empty lines
c: |
# this is not a comment
it is the first line of a block style literal scalar
processing this gobbles a newline which doesn't go into a comment
# that is unless you have a (dedented) comment directly following
d: 42 # and some non-full line comment
e: # another one
# and some more comments to align
f: glitter in the dark near the Tannhäuser gate
I am a teacher that is writing a program to read an 8-digit ID barcode for students who are late to school. I am an experienced programmer, but new to Python and very new to Tkinter (about 36 hours experience) I have made heavy use of this site so far, but I have been unable to find the answer to this question:
How can I read exactly 8 digits, and display those 8 digits in a textbox immediately. I can do 7, but can't seem to get it to 8. Sometimes, I will get nothing in the text box. I have used Entry, bind , and everything works OK, except I can't seem to get the keys read in the bind event to place the keys in the textbox consistently that were inputted. The ID seems to be always correct when I PRINT it, but it is not correct in the textbox. I seem unable to be allowed to show the tkinter screen, so it shows only 7 digits or nothing in the text box upon completion.
Here is a snippet of my code, that deals with the GUI
from tkinter import *
from collections import Counter
import time
i=0
class studentNumGUI():
def __init__(self, master):
master.title("Student ID Reader")
self.idScanned = StringVar()
localTime = time.asctime(time.localtime(time.time()))
self.lblTime = Label(master, text=localTime)
self.lblTime.pack()
self.lbl = Label(master, text="Enter Student ID:")
self.lbl.pack()
self.idScanned.set("")
self.idScan = Entry(master,textvariable=self.idScanned,width=12)
self.idScan.pack()
self.frame=Frame(width=400,height=400)
self.frame.pack()
self.frame.focus()
self.frame.bind('<Key>',self.key)
def key(self,event):
global i
self.frame.focus()
self.idScan.insert(END,event.char)
print(repr(event.char)," was pressed") #just to make sure that my keystrokes are accepted
if (i < 7):
i += 1
else:
#put my other python function calls here once I fix my problem
self.frame.after(2000)
#self.idScan.delete(0,END) #Then go blank for the next ID to be read
i=0
root = Tk()
nameGUI = studentNumGUI(root)
root.mainloop()
enter image description here
You are doing some unusual things in order to place text inside the Entry field based on keypresses. I've changed your code so that it sets the focus on the Entry widget and will check the contents of the Entry field each time a key is pressed (while the Entry has focus). I'm then getting the contents of the Entry field and checking if the length is less than 8. If it is 8 (or greater) it will clear the box.
How does this work for you?
I've left in the commented out code
from tkinter import *
from collections import Counter
import time
class studentNumGUI():
def __init__(self, master):
master.title("Student ID Reader")
self.idScanned = StringVar()
localTime = time.asctime(time.localtime(time.time()))
self.lblTime = Label(master, text=localTime)
self.lblTime.pack()
self.lbl = Label(master, text="Enter Student ID:")
self.lbl.pack()
self.idScanned.set("")
self.idScan = Entry(master,textvariable=self.idScanned,width=12)
self.idScan.pack()
self.idScan.focus_set()
self.frame=Frame(width=400,height=400)
self.frame.pack()
#self.frame.focus()
#self.frame.bind('<Key>',self.key)
self.idScan.bind('<Key>',self.key)
def key(self,event):
#self.frame.focus()
#self.idScan.insert(END,event.char)
print(repr(event.char)," was pressed") #just to make sure that my keystrokes are accepted
len(self.idScanned.get())
if (len(self.idScanned.get())<8):
pass
else:
#put my other python function calls here once I fix my problem
self.idScan.delete(0,END) #Then go blank for the next ID to be read
#self.frame.after(2000)
root = Tk()
nameGUI = studentNumGUI(root)
root.mainloop()
Geany is a simple, fast and yet powerful text editor.
It has quite strong support for syntax highlighting for almost all kinds
of programming languages.
I was wondering how to make a customized syntax highlighting for my
special need program called "Phosim" which has the file extension .cat.
So far I have done this:
First I created filetype extension configuration file: ~/.config/geany/filetype_extensions.conf
The contents of this looks like this:
[Extensions]
Gnuplot=*.gp;*.gnu;*.plt;
Galfit=*.gal;
Phosim=*.cat;
[Groups]
Script=Gnuplot;Galfit;Phosim;
Here, I am trying to apply custom highlight to programs Gnuplot, Galfit, and Phosim. For Gnuplot and Galfit it works fine. But for Phosim I got some problems.
Then I created file definition configuration file: ~/.config/geany/filedefs/filetypes.Phosim.conf
The contents of which looks like this:
# Author : Bhishan Poudel
# Date : May 24, 2016
# Version : 1.0
[styling]
# Edit these in the colorscheme .conf file instead
default=default
comment=comment_line
function=keyword_1
variable=string_1,bold
label=label
userdefined=string_2
number=number_2
[keywords]
# all items must be in one line separated by space
variables=object Unrefracted_RA_deg SIM_SEED none
functions=
lables=10
userdefined=angle 30 Angle_RA 20.0 none
numbers=0 1 2 3 4 5 6 7 8 9
[lexer_properties]
nsis.uservars=1
nsis.ignorecase=1
[settings]
# default extension used when saving files
extension=cat
# single comments, like # in this file
comment_single=#
# multiline comments
#comment_open=
#comment_close=
# This setting works only for single line comments
comment_use_indent=true
# context action command (please see Geany's main documentation for details)
context_action_cmd=
# lexer filetype should be an existing lexer that does not use lexer_filetype itself
lexer_filetype=NSIS
[build-menu]
EX_00_LB=Execute
EX_00_CM=
EX_00_WD=
FT_00_LB=
FT_00_CM=
FT_00_WD=
FT_02_LB=
FT_02_CM=
FT_02_WD=
Now my example.cat looks like this:
# example.cat
angle 30
Angle_RA 20.0
object none
# Till now,
# Words highlighted : angle 30 object none
# Words not highlighted: Angle_RA 20.0
# I like them also to be highlighted!
I got syntax highlighting for only two words, viz., object and none.
I tried styling equal to Fortran since it has uppercase letters but it also did not work.
How can we get the syntax highlight for the variable names which contains uppercase, lowercase, and underscore?
For example:
I got syntax highlight for words: object none.
But, did not get syntax highlight for words: Angle_RA 20.0
Also, I my numbers 0,1,..,9 are highlighted but the decimals are not highlighted. How can we highlight decimals too?
For example:
I got syntax highlight for words: 1 1000 but, did not get syntax highlight for words: 49552.3 180.0
Some useful links are following:
Make Geany recognize additional file extensions
Custom syntax highlighting in Geany
http://www.geany.org/manual/current/index.html#custom-filetypes
http://www.geany.org/manual/#lexer-filetype
Instead of creating new file definition files I added file extensions for Python and it worked for me.
For example, I wanted to custom highlight the files with extension .icat (If you are interested, this is instance catalog file for Phosim Software in Astronomy.)
Drawback: The additional words are also highlighted in python scripts (.py,.pyc,.ipy)
Note: If anybody posts solution that works with new file extension, ~/.config/geany/filedefs/filetypes.Phosim.conf I would heartly welcome that.
My example.pcat file looks like this:
# example.pcat
Unrefracted_RA_deg 0
Unrefracted_Dec_deg 0
Unrefracted_Azimuth 0
Unrefracted_Altitude 89
Slalib_date 1994/7/19/0.298822999997
Opsim_rotskypos 0
Opsim_rottelpos 0
Opsim_moondec -90
Opsim_moonra 180
Opsim_expmjd 49552.3
Opsim_moonalt -90
Opsim_sunalt -90
Opsim_filter 2
Opsim_dist2moon 180.0
Opsim_moonphase 10.0
Opsim_obshistid 99999999
Opsim_rawseeing 0.65
SIM_SEED 1000
SIM_MINSOURCE 1
SIM_TELCONFIG 0
SIM_CAMCONFIG 1
SIM_VISTIME 15000.0
SIM_NSNAP 1
object 0 0.0 0.0 20 ../sky/sed_flat.txt 0 0 0 0 0 0 bhishan.fits 0.09 0.0 none
I want geany to highlight all first words with yellow color, numbers with mangenta, and the word 'none' with blue color.
First I created (or, edited if already exists) the file:
~/.config/geany/filetype_extensions.conf
And added following stuff inside it.
[Extensions]
Gnuplot=*.gp;*.gnu;*.plt;
Galfit=*.gal;
Phosim=*.pcat;
Python=*.py;*.pyc;*.ipy;*.icat;*.pcat
[Groups]
Script=Gnuplot;Galfit;Phosim;Python;
Then, I added the additional KEYWORDS to the already existing keywords in python filetype.
For this I created (or, edited if already exists) the file:
~/.config/geany/filedefs/filetypes.python
Now, the file ~/.config/geany/filedefs/filetypes.python looks like this:
# Author : Bhishan Poudel
# Date : June 9, 2016
# Version : 1.0
# File : Filetype for both python and phosim_instance_catalogs
[styling]
default=default
commentline=comment_line
number=number_1
string=string_1
character=character
word=keyword_1
triple=string_2
tripledouble=string_2
classname=type
defname=function
operator=operator
identifier=identifier_1
commentblock=comment
stringeol=string_eol
word2=keyword_2
decorator=decorator
[keywords]
# all items must be in one line
primary=and as assert break class continue def del elif else except exec finally for from global if import in is lambda not or pass print raise return try while with yield False None True Words_after_this_are_for_Phosim_pcat_files Unrefracted_RA_deg Unrefracted_Dec_deg Unrefracted_Azimuth Unrefracted_Altitude Slalib_date Opsim_moondec Opsim_rotskypos Opsim_rottelpos Opsim_moondec Opsim_moonra Opsim_expmjd Opsim_moonalt Opsim_sunalt Opsim_filter Opsim_dist2moon Opsim_moonphase Opsim_obshistid Opsim_rawseeing SIM_SEED SIM_MINSOURCE SIM_TELCONFIG SIM_CAMCONFIG SIM_VISTIME SIM_NSNAP object
identifiers=ArithmeticError AssertionError AttributeError BaseException BufferError BytesWarning DeprecationWarning EOFError Ellipsis EnvironmentError Exception FileNotFoundError FloatingPointError FutureWarning GeneratorExit IOError ImportError ImportWarning IndentationError IndexError KeyError KeyboardInterrupt LookupError MemoryError NameError NotImplemented NotImplementedError OSError OverflowError PendingDeprecationWarning ReferenceError RuntimeError RuntimeWarning StandardError StopIteration SyntaxError SyntaxWarning SystemError SystemExit TabError TypeError UnboundLocalError UnicodeDecodeError UnicodeEncodeError UnicodeError UnicodeTranslateError UnicodeWarning UserWarning ValueError Warning ZeroDivisionError __debug__ __doc__ __import__ __name__ __package__ abs all any apply basestring bin bool buffer bytearray bytes callable chr classmethod cmp coerce compile complex copyright credits delattr dict dir divmod enumerate eval execfile exit file filter float format frozenset getattr globals hasattr hash help hex id input int intern isinstance issubclass iter len license list locals long map max memoryview min next object oct open ord pow print property quit range raw_input reduce reload repr reversed round set setattr slice sorted staticmethod str sum super tuple type unichr unicode vars xrange zip array arange Catagorical cStringIO DataFramedate_range genfromtxt linspace loadtxt matplotlib none numpy np pandas pd plot plt pyplot savefig scipy Series sp StringIO
[lexer_properties]
fold.comment.python=1
fold.quotes.python=1
[settings]
# default extension used when saving files
extension=py
# the following characters are these which a "word" can contains, see documentation
wordchars=_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
# MIME type
mime_type=text/x-python
comment_single=#
comment_open="""
comment_close="""
comment_use_indent=true
# context action command (please see Geany's main documentation for details)
context_action_cmd=
[indentation]
width=4
# 0 is spaces, 1 is tabs, 2 is tab & spaces
type=0
[build_settings]
# %f will be replaced by the complete filename
# %e will be replaced by the filename without extension
# (use only one of it at one time)
compiler=python -m py_compile "%f"
run_cmd=python "%f"
[build-menu]
FT_00_LB=Execute
FT_00_CM=python %f
FT_00_WD=
FT_01_LB=
FT_01_CM=
FT_01_WD=
FT_02_LB=
FT_02_CM=
FT_02_WD=
EX_00_LB=Execute
EX_00_CM=clear; python %f
EX_00_WD=
error_regex=([^:]+):([0-9]+):([0-9:]+)? .*
EX_01_LB=
EX_01_CM=
EX_01_WD=
Now, I restarted the geany and I can see all the first words in yellow, numbers other color and the word 'none' is blue colored.