Editor (Sublime, Notepad++, etc.) Paste 'around' existing text - python

Motivation: I was going around assigning parameters read in from a config file to variables in a function like so:
john = my_quest
terry = my_fav_color
eric = airspeed
ni = swallow_type
...
when I realized this was going to be a lot of parameters to pass. I thus decided I'd put these parameters in a nice dictionary, grail, e.g. grail['my_quest'] so that the only thing I needed to pass to the function was grail.
Question: Is there a simple way in Sublime (or Notepad++, Spyder, Pycharm, etc.) to paste grails['variable'] around those variables in one step, instead of needing to paste the front and back seperately? (I know about multiple cursors in Sublime, that does help, but I'd love to find a "highlight-variable-and-hit-ctrl-meta-shift-\" and it's done.)

Based on examples you provided, this is a simple task solvable using standard regex find/replace.
So in Notepad++, record this macro (for recording control examine Macro menu):
Press Ctrl+H to open Find/Replace dialog
Find what: = (.*)$
Replace with: = grail['\1']
Choose Regular Expression and press Replace All
If you finish recording the macro and you choose to save it, shortcut key is requested. Assign your favorite ctrl-meta-shift-\ and you are done.

Related

Vim fastest way to replace words

Sometimes I find myself wanting to replace just 2-3 long words in a program and I find it a bit painful in how I do it, just wondering if there is any Vim wizards out there that could give me a faster way of doing this:
var_wanted = {}
some_other_var = {}
def function1():
....
....
some_other_var.append(...)
....
some_other_var.append(...)
some_other_var.append(...)
....
Now lets say I want to replace some_other_var with var_wanted, now usually the way I do this is I will go to var_wanted use yiw to copy the word to register, then move to the first instance of some_other_var do viw to select the word, then do p to paste it in and replace the word. However this process is not repeatable, I can't go to the next instance of some_other_var and type . because for some reason now some_other_var is in my register as opposed to var_wanted, I do this so often that I feel like I'm losing years of my life. And yes I am aware of using search and replace :%s/some_other_var/var_watned/gc, but I feel like this instance is for so few replacements that its not worth typing that whole thing out. Please heeelp
End product wanted:
var_wanted = {}
some_other_var = {}
def function1():
....
....
var_wanted.append(...)
....
var_wanted.append(...)
var_wanted.append(...)
....
TL;DR:
Cursor on var_wanted: "ayiw (yank into register a).
Cursor on some_old_var: ciwCtrlraEsc (change word, insert contents of register a).
Put cursor on next some_old_var: . will do the previous action again.
Finding a keystroke series that's shorter than %s/some_old_var/var_wanted/g is going to be difficult.
because for some reason now some_other_var is in my register
viwp is implicitly deleting the selected word. Deleted text in vim goes into the register. You can avoid this with viw"_dP instead, which explicitly deletes into the null register so it does not get copied, and then puts. Typing this 3 times seems worse than the %s/ version.
If it's typing var_wanted and some_other_var that bothers you, you can yank them into registers (let's use "find and "replace for mnemonic purposes) via "fyiw and "ryiw when your cursor is in the right spots. Then you could just %s:<C-r>f:<C-r>r:g to do all the replaces (<C-R> means Ctrlr). The problem here is moving the cursor around and then yanking doesn't seem much faster than typing the word.
There's also changing things. If you had some_old_var., you could position your cursor on the word and then ciwvar_wanted, which would remove some_old_var and enter insert mode where you would type var_wanted. The benefit to this is after leaving insert mode, you could use . when your cursor is on the next instance of some_old_var and it would repeat the whole action, replacing some_old_var with var_wanted.
Another useful note is that if var_wanted is super long (and exists in this file already), you can use C-n to autocomplete after you've typed a few characters of the word. This would still work with . after you finished the insert.
If you really want to avoid typing any amount of var_wanted, you can use the Ctrlr in insert mode as well, meaning you can yank var_wanted by putting your cursor on it and using "ayiw (to yank into register a) and then putting your cursor on some_old_var and doing ciw<C-R>a to replace it.
As long as your desired register is the yank register:
:%s/some_other_var/\=#0/g
The above solution is good if you are trying to change a large number of occurences of the "some_other_var"
You can also use the "gn" approach, see :h gn, in my case I have:
:nnoremap c* *<c-o>cgn
copy the "var_wanted" move to the first "some_other_var" and then press:
c* ...................... triggers our mapping
<Ctrl-r>0 ................ paste the yank register
<Esc> .................... leave insert mode
. ....................... now press dot as much as you want
To learn more about the gn trick watch this amazing video:
http://vimcasts.org/episodes/operating-on-search-matches-using-gn/

Python virtual keyboard -- issue with triple-key expression Ctrl-Shift-Home

I have been using a virtual keyboard that uses ctypes in Python 3.3 for a while, and I can't get it to do Ctrl-Shift-Home, among other triple-key expressions, like Ctrl-Alt-Delete. The expression Ctrl-Shift-Home selects the text starting at the cursor going back to the beginning of the text---which works when I press the expression manually, but I cannot get my code to do it.
My code is essentially the same as the code from this stackoverflow answer, and then to do the expression I could do something like
def Ctrl_Shift_Home():
PressKey(0x11) # Ctrl
PressKey(0x10) # Shift
PressKey(0x24) # Home
time.sleep(0.1)
ReleaseKey(0x24)
ReleaseKey(0x10)
ReleaseKey(0x11)
But the above does not select any text. Is this an issue with the code itself, or an issue with triple-key expressions, or is selecting text just not allowed using keyboard events?
Any answers or alternatives would be appreciated! Thank you!

Vim and python - jump to definition key binding

The following youtube video shows that it is possible to jump to definition using vim for python.
However when I try the same shortcut (Ctrl-G) it doesnt work...
How is it possible to perform the same "jump to definition"?
I installed the plugin Ctrl-P but not rope.
This does not directly answer your question but provides a better alternative. I use JEDI with VIM, as a static code analyser, it offers far better options than ctags. I use the spacemacs key-binding in vim so with localleader set to ','
" jedi
let g:jedi#use_tabs_not_buffers = 0 " use buffers instead of tabs
let g:jedi#show_call_signatures = "1"
let g:jedi#goto_command = "<localleader>gt"
let g:jedi#goto_assignments_command = "<localleader>ga"
let g:jedi#goto_definitions_command = "<localleader>gg"
let g:jedi#documentation_command = "K"
let g:jedi#usages_command = "<localleader>u"
let g:jedi#completions_command = "<C-Space>"
let g:jedi#rename_command = "<leader>r"
Vim's code navigation is based on a universal database called tags file. It needs to be generated (and updated) manually. :help ctags lists some applications that can do that. Exuberant ctags is a common one that supports many programming languages, but there are also specialized ones, like ptags.py (found in your Python source directory at Tools/scripts/ptags.py).
Plugins like easytags.vim provide more convenience by e.g. automatically updating the tags file on each save.
The default command for jumping to the definition is CTRL-] (not CTRL-G; that prints the current filename; see :help CTRL-G), or the Ex command :tag {identifier}; see all at :help tag-commands.
Some suggestions for people reading other answers to this question in the future:
tags file has one limitation. If in your code multiple objects has the same name you will have problem using ctrl-] as it will jump to first one and not necessary correct one. In this situation you can use g ctrl-] (or :tjump command or :tselect command) to get selection list. Potentially you want to map ctrl-] to "g ctrl-]"
It is possible that you want to have possibility to jump to correct object. In that case you might want to use jedi vim and if you are used to c-] you might want to use this mapping for jedi goto let g:jedi#goto_command = ""
Lastly you want to use universal ctags instead of excuberant ctags because of better new files support (not necessary python).
If you're using YouCompleteMe there is a command for that
:YcmCompleter GoToDefinition
if you want to add a shortcut for doing that in a new tab
nnoremap <leader>d :tab split \| YcmCompleter GoToDefinition<CR>

Printing in Duplexpage a word document

I am trying to automate the task of printing two copies at double page of ~30 Word document (*.doc). I want to send the program converted to .exe (I plan it just for Windows computers) using py2exe. I know that I can manually check the options but I will not be able to do so on the 20 or so computer where it will be used, as well as I cannot install in this computers new software (That's why I want to convert it into .exe).
I copied this solution to print, but I can't adapt it to do what I want:
from win32com import client
import time
word = client.Dispatch("Word.Application")
filename=input("What files do you want to print?")
def printWordDocument(filename):
"""Given a name of a file prints it. TODO: Add double page."""
word.Documents.Open(filename)
word.ActiveDocument.PrintOut()
time.sleep(2)
word.ActiveDocument.Close()
word.Quit()
I couldn't find any option to print in double pages, or at least automatically, the only option of double page of PrintOut method is ManualDuplexPrint which in the documentation says: "True to print a two-sided document on a printer without a duplex printing kit.", but I don't want to make it even easier to print all the set of documents. And make a program portable to other computers, without modifying the Word documents (I don't create them).
Any other way to do it? Or any other option to do it?
UPDATE
I am not able to code in visual-basic (yet), but if I get a template or some hints I think I will manage to make something adapted to my conditions.
I have ended doing a macro, but this just works for my own computer and not for all the computers where should work.
Sub Test()
'
' Test Macro
' Print in double page and 2 copies
'
ActivePrinter = "Xerox WC 24 PCL"
Application.PrintOut FileName:="", Range:=wdPrintAllDocument, Item:= _
wdPrintDocumentWithMarkup, Copies:=2, Pages:="", PageType:= _
wdPrintAllPages, Collate:=True, Background:=True, PrintToFile:=False, _
PrintZoomColumn:=0, PrintZoomRow:=0, PrintZoomPaperWidth:=0, _
PrintZoomPaperHeight:=0
End Sub

Extracting data from MS Word

I am looking for a way to extract / scrape data from Word files into a database. Our corporate procedures have Minutes of Meetings with clients documented in MS Word files, mostly due to history and inertia.
I want to be able to pull the action items from these meeting minutes into a database so that we can access them from a web-interface, turn them into tasks and update them as they are completed.
Which is the best way to do this:
VBA macro from inside Word to create CSV and then upload to the DB?
VBA macro in Word with connection to DB (how does one connect to MySQL from VBA?)
Python script via win32com then upload to DB?
The last one is attractive to me as the web-interface is being built with Django, but I've never used win32com or tried scripting Word from python.
EDIT: I've started extracting the text with VBA because it makes it a little easier to deal with the Word Object Model. I am having a problem though - all the text is in Tables, and when I pull the strings out of the CELLS I want, I get a strange little box character at the end of each string. My code looks like:
sFile = "D:\temp\output.txt"
fnum = FreeFile
Open sFile For Output As #fnum
num_rows = Application.ActiveDocument.Tables(2).Rows.Count
For n = 1 To num_rows
Descr = Application.ActiveDocument.Tables(2).Cell(n, 2).Range.Text
Assign = Application.ActiveDocument.Tables(2).Cell(n, 3).Range.Text
Target = Application.ActiveDocument.Tables(2).Cell(n, 4).Range.Text
If Target = "" Then
ExportText = ""
Else
ExportText = Descr & Chr(44) & Assign & Chr(44) & _
Target & Chr(13) & Chr(10)
Print #fnum, ExportText
End If
Next n
Close #fnum
What's up with the little control character box? Is some kind of character code coming across from Word?
Word has a little marker thingy that it puts at the end of every cell of text in a table.
It is used just like an end-of-paragraph marker in paragraphs: to store the formatting for the entire paragraph.
Just use the Left() function to strip it out, i.e.
Left(Target, Len(Target)-1))
By the way, instead of
num_rows = Application.ActiveDocument.Tables(2).Rows.Count
For n = 1 To num_rows
Descr = Application.ActiveDocument.Tables(2).Cell(n, 2).Range.Text
Try this:
For Each row in Application.ActiveDocument.Tables(2).Rows
Descr = row.Cells(2).Range.Text
Well, I've never scripted Word, but it's pretty easy to do simple stuff with win32com. Something like:
from win32com.client import Dispatch
word = Dispatch('Word.Application')
doc = word.Open('d:\\stuff\\myfile.doc')
doc.SaveAs(FileName='d:\\stuff\\text\\myfile.txt', FileFormat=?) # not sure what to use for ?
This is untested, but I think something like that will just open the file and save it as plain text (provided you can find the right fileformat) – you could then read the text into python and manipulate it from there. There is probably a way to grab the contents of the file directly, too, but I don't know it off hand; documentation can be hard to find, but if you've got VBA docs or experience, you should be able to carry them across.
Have a look at this post from a while ago: http://mail.python.org/pipermail/python-list/2002-October/168785.html Scroll down to COMTools.py; there's some good examples there.
You can also run makepy.py (part of the pythonwin distribution) to generate python "signatures" for the COM functions available, and then look through it as a kind of documentation.
You could use OpenOffice. It can open word files, and also can run python macros.
I'd say look at the related questions on the right -->
The top one seems to have some good ideas for going the python route.
how about saving the file as xml. then using python or something else and pull the data out of word and into the database.
It is possible to programmatically save a Word document as HTML and to import the table(s) contained into Access. This requires very little effort.

Categories

Resources